2011-07-25 86 views
3

我已經搜索過,無法找到此問題的具體答案。我有一個模型,它有一個名爲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循環中得到一個運行時錯誤,「對象引用未設置爲對象的實例」。

這是怎麼回事。謝謝。另外,還有更好的方法來完成這個嗎?

+0

我想,當你將窗體你得到這個錯誤,而不是正確的過嗎? –

+0

此答案可能提供您需要的信息:http://stackoverflow.com/questions/962189/how-do-i-bind-a-dictionary-to-a-set-of-checkboxes-using-asp-net- mvc –

+0

這也是:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx –

回答