最近在用mvc3做項目,常走一些彎路,在此記錄View傳參數到Controller中的Action,Action接收參數的四種方式
1.示例model
public class testModel
{
public String A { get; set; }
public String B { get; set; }
public String C { get; set; }
public String D { get; set; }
}
2.示例View
@{
ViewBag.Title = "test1";
}
@model MvcApplication2.Models.testModel
<h2>test1</h2>
@using (Html.BeginForm())
{
<table>
<tr>
<td><input type="text" name="A" /></td>
<td><input type="text" name="B" /></td>
<td><input type="text" name="C" /></td>
<td><input type="text" name="D" /></td>
</tr>
<tr>
<td colspan="4"><input type="submit" value="提交" /></td>
</tr>
</table>
}
3.示例Controller
public class TestController : Controller
{
/// <summary>
/// 視圖傳遞參數到控制器中的Aciton的第四種方式 form post提交 model參數接收
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public ActionResult test1(testModel t)
{
String a = t.A;
String b = t.B;
String c = t.C;
String d = t.D;
return View();
}
///// <summary>
///// 視圖傳遞參數到控制器中的Aciton的第三種方式 form提交 方法參數接收
///// </summary>
///// <param name="A"></param>
///// <param name="B"></param>
///// <param name="C"></param>
///// <param name="D"></param>
///// <returns></returns>
//public ActionResult test1(String A,String B,String C,String D)
//{
// String a = A;
// String b = B;
// String c = C;
// String d = D;
// return View();
//}
///// <summary>
///// 視圖傳遞參數到控制器中的Aciton的第二種方式 form post提交 request.form接收
///// </summary>
///// <returns></returns>
//public ActionResult test1()
//{
// String a = Request.Form["A"];
// String b = Request.Form["B"];
// String c = Request.Form["C"];
// String d = Request.Form["D"];
// return View();
//}
///// <summary>
///// 視圖傳遞參數到控制器中的Aciton的第一種方式 form post提交 FormCollection接收
///// </summary>
///// <param name="frm"></param>
///// <returns></returns>
//public ActionResult test1(FormCollection frm)
//{
// String a = frm["A"];
// String b = frm["B"];
// String c = frm["C"];
// String d = frm["D"];
// return View();
//}
}
注:本人推薦使用第四方法,進行接收傳過來的參數