【C#】ViewからControllerへ値を渡す方法
今回はViewからControllerへ値を渡す方法をこの記事で説明します。
この記事のポイント・View、Controller、Modelの使用
ViewからControllerへ値を渡す方法
Modelを介さない場合
以下のようにViewを設定します。
<input name="userid" type="text" value="000001" />
<input name="usernm" type="text" value="千葉太郎" />
Controller側の設定
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Action1(string userid, string username)
{
// Viewに設定したnameと一致させることによってControllerで値を取得できる。
HttpContext.Session.Add("_uid", userid);
HttpContext.Session.Add("_unm", username);
return RedirectToAction("NextPagge", "NextPage")
}
Modelを使用する場合
以下のようにModelを追加します。
public class UserInfo
{
public string userid { get; set; }
public string username { get; set; }
}
Controller側の設定
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Action1(UserInfo model)
{
// Viewに設定したnameと一致させることによってControllerで値を取得できる。
HttpContext.Session.Add("_uid", model.userid);
HttpContext.Session.Add("_unm", model.username);
return RedirectToAction("NextPagge", "NextPage")
}
これでViewからControllerへ値を渡すことが出来るようになります。
< |