我已经搜索过,但找不到这个问题的具体答案。我有一个模型,它有一个名为 Weekdays 的字典对象,我想将其映射到一组表单字段,其中键是日期,值是是否选中。
所以表单看起来像这样:
Monday [ ]
Tuesday [ ]
Wednesday [ ]
Thursday [ ]
Friday [ ]
我的模型如下所示:
public class Event
{
[Required(ErrorMessage="All must be checked")]
public Dictionary<string,bool> Weekdays { get; set; }
}
Controller :
namespace MvcApplication6.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Event e = new Event();
e.Name = "awesome";
e.Weekdays = new Dictionary<string, bool>()
{
{"Monday", false },
{"Tuesday", true },
{"Wednesday", true },
{"Thursday", false },
{"Friday", true },
};
return View("Home", e);
}
[HttpPost]
public ActionResult Index(Event e)
{
var x = e.Weekdays["Monday"];
return View("Home", e);
}
}
}
我的看法:
@model MvcApplication6.Models.Event
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<style>.formErrors{color:Red}</style>
<title>Home</title>
</head>
<body>
<div>
@using (@Html.BeginForm("Index", "Home"))
{
// Weekdays
foreach (var i in Model.Weekdays)
{
@i.Key @Html.EditorFor(model => model.Weekdays[i.Key]) <br />
}
<br /><br /><br />
<input type="submit" value="submit me" />
}
</div>
</body>
</html>
目前,我在 foreach 循环中遇到运行时错误,“对象引用未设置为对象的实例。”
这是怎么回事。谢谢。另外,有没有更好的方法来做到这一点?
最佳答案
看看这篇文章ASP.NET MVC Model Binder not working with a dictionary 您还可以为字典编写自己的模型绑定(bind)器,这是一个示例 http://siphon9.net/loune/2010/11/dictionary-model-binder-in-asp-net-mvc2-and-mvc3/
关于asp.net - 使用字典将复选框绑定(bind)到对象的问题模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6818746/