fea*_*net 17 int checkbox ienumerable model-binding asp.net-mvc-3
@Html.CheckBox("orderNumbers", new { value = 1 })
@Html.CheckBox("orderNumbers", new { value = 2 })
@Html.CheckBox("orderNumbers", new { value = 3 })
@Html.CheckBox("orderNumbers", new { value = 4 })
@Html.CheckBox("orderNumbers", new { value = 5 })
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<int> orderNumbers) { }
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<string> orderNumbers) { }
Run Code Online (Sandbox Code Playgroud)
如果我在我的动作方法中使用第一个签名,我会得到一个空的IEnumerable.
如果我使用第二个签名,我确实收到了值,但我也收到了未选择值的假值(因为MVCs模式阴影所有复选框都带有隐藏字段).
我会收到类似的东西 orderNumbers = { "1", "2", "false", "4", "false" }
为什么我不能得到数字列表?
alo*_*ida 24
您可以通过以下方式获取所有选中的值.
控制器代码:
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string[] orderNumbers)
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
查看代码:
@using (Html.BeginForm())
{
<input name="orderNumbers" type="checkbox" value="1" />
<input name="orderNumbers" type="checkbox" value="2" />
<input name="orderNumbers" type="checkbox" value="3" />
<input name="orderNumbers" type="checkbox" value="4" />
<input name="orderNumbers" type="checkbox" value="5" />
<input type="submit" name="temp" value="hi" />
}
Run Code Online (Sandbox Code Playgroud)
请记住一件事,你需要为所有复选框指定相同的名称.在数组中,您将获得所有选中复选框的值.
除了alok_dida的好答案.由于所有值都是整数,因此您可以让控制器代码采用整数数组,并避免自己进行转换.
这适用于MVC4 +:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int[] orderNumbers)
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16140 次 |
| 最近记录: |