问题模型将复选框绑定到带有字典的对象

时间:2011-07-25 15:46:34

标签: asp.net asp.net-mvc-3 razor

我搜索了SO,但找不到这个问题的具体答案。我有一个名为Weekdays的字典对象的模型,我希望将其映射到一组表单字段,其中键是日期,值是否被检查过。

所以表格看起来像这样:

Monday [ ]
Tuesday [ ]
Wednesday [ ]
Thursday [ ]
Friday [ ]

我的模型看起来像这样:

public class Event
{
  [Required(ErrorMessage="All must be checked")]    
  public Dictionary<string,bool> Weekdays { get; set; }
}

控制器:

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循环上遇到运行时错误,“对象引用未设置为对象的实例。”

这是什么交易。谢谢。另外,有没有更好的方法来完成这项工作?

1 个答案:

答案 0 :(得分:1)

看看这篇文章ASP.NET MVC Model Binder not working with a dictionary 您也可以编写自己的Model Binder for Dictionary,这是一个例子http://siphon9.net/loune/2010/11/dictionary-model-binder-in-asp-net-mvc2-and-mvc3/