Problem Model Binding Checkboxes to Object with Dictionary
I've searched SO and couldn't find a specific answer to this problem. I have a model that has a dictionary object called Weekdays and I want to map that to a set of form fields where the key is the day and the value is if it was checked or not.
So the form looks like this:
Monday [ ]
Tuesday [ ]
Wednesday [ ]
Thursday [ ]
Friday [ ]
My model looks like this:
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 },
{"Wednesda开发者_运维百科y", true },
{"Thursday", false },
{"Friday", true },
};
return View("Home", e);
}
[HttpPost]
public ActionResult Index(Event e)
{
var x = e.Weekdays["Monday"];
return View("Home", e);
}
}
}
My view:
@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>
Currently, I'm getting a runtime error on the foreach loop, "Object reference not set to an instance of an object."
What's the deal. Thanks. Also, is there a better way to do this altogether?
Look at this post ASP.NET MVC Model Binder not working with a dictionary You can also write your own Model Binder for Dictionary, here's an example http://siphon9.net/loune/2010/11/dictionary-model-binder-in-asp-net-mvc2-and-mvc3/
精彩评论