有没有什么办法可以绑定一个复选框列表在asp.net模型MVC [英] Is there any way to bind a checkbox list to a model in asp.net mvc
问题描述
我期待在这里找到一个快速简便的方法,当回发发生在模型绑定复选框列表项的列表。
I am looking here to find a quick and easy way to bind a list of checkbox list items when the postback occurs in the model.
显然,现在就这样做了常用的方法似乎不喜欢这样 form.GetValues(的CheckBoxList)[0]。载(真);
这看起来不好受,而不是完全安全的。
Apparently the common way to do it now seems to do it like this form.GetValues("checkboxList")[0].Contains("true");
It seems painfull and not exactly safe.
有没有办法绑定复选框的列表(被带或不带视图的助手创建),或该数据甚至阵列中的的UpdateModel(myViewModel,form.ToValueProvider事项());
阶段这将填充一个的IList<字符串>
或的String []
内部模型的
Is there a way to bind a list of checkbox (that are created with or without an helper in the view) or even an array of data for that matters during the UpdateModel(myViewModel, form.ToValueProvider());
phase which would populate an IList<string>
or string[]
inside of the model ?
推荐答案
您可以从一个模型:
public class MyViewModel
{
public int Id { get; set; }
public bool IsChecked { get; set; }
}
然后控制器:
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { Id = 1, IsChecked = false },
new MyViewModel { Id = 2, IsChecked = true },
new MyViewModel { Id = 3, IsChecked = false },
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
// TODO: Handle the user selection here
...
}
}
视图(〜/查看/首页/的Index.aspx
):
<% using (Html.BeginForm()) { %>
<%=Html.EditorForModel() %>
<input type="submit" value="OK" />
<% } %>
最后一个相应的编辑模板:
And finally a corresponding editor template:
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.MyViewModel>" %>
<%= Html.HiddenFor(x => x.Id) %>
<%= Html.CheckBoxFor(x => x.IsChecked) %>
现在,当您在POST动作提交表单,你会得到选定值的列表以及它们的ID。
Now when you submit the form in the POST action you will get the list of selected values along with their id.
这篇关于有没有什么办法可以绑定一个复选框列表在asp.net模型MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!