2011-07-28 34 views
3

我想定義一個顯示標籤和複選框列表的視圖,用戶可以更改複選框,然後回發。我有問題發回字典。也就是說,post方法的字典參數爲null。如何爲ASP.NET MVC上的GET和POST操作綁定字典類型參數

下面是操作方法爲GET和POST操作:

public ActionResult MasterEdit(int id) 
     { 

      Dictionary<string, bool> kv = new Dictionary<string, bool>() 
              { 
               {"A", true}, 
               {"B", false} 
              }; 

      return View(kv); 
     } 


     [HttpPost] 
     public ActionResult MasterEdit(Dictionary<string, bool> kv) 
     { 
      return RedirectToAction("MasterEdit", new { id = 1 }); 
     } 

Beliw是視圖

@model System.Collections.Generic.Dictionary<string, bool> 
@{ 
    ViewBag.Title = "Edit"; 
} 
<h2> 
    MasterEdit</h2> 

@using (Html.BeginForm()) 
{ 

    <table> 
     @foreach(var dic in Model) 
     { 
      <tr> 
       @dic.Key <input type="checkbox" name="kv" value="@dic.Value" /> 
      </tr> 


     } 
    </table> 


    <input type="submit" value="Save" /> 
} 

任何想法將是非常非常感謝!

回答

5

請勿爲此使用字典。模型綁定效果不佳。可能是PITA。

視圖模型將更爲合適:

public class MyViewModel 
{ 
    public string Id { get; set; } 
    public bool Checked { get; set; } 
} 

然後控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new[] 
     { 
      new MyViewModel { Id = "A", Checked = true }, 
      new MyViewModel { Id = "B", Checked = false }, 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(IEnumerable<MyViewModel> model) 
    { 
     return View(model); 
    } 
} 

然後一個相應的視圖(~/Views/Home/Index.cshtml):

@model IEnumerable<MyViewModel> 

@using (Html.BeginForm()) 
{ 
    <table> 
     <thead> 
      <tr> 
       <th></th> 
      </tr> 
     </thead> 
     <tbody> 
      @Html.EditorForModel() 
     </tbody> 
    </table> 
    <input type="submit" value="Save" /> 
} 

,最後相應的編輯器模板(~/Views/Home/EditorTemplates/MyViewModel.cshtml):

@model MyViewModel 
<tr> 
    <td> 
     @Html.HiddenFor(x => x.Id) 
     @Html.CheckBoxFor(x => x.Checked) 
     @Html.DisplayFor(x => x.Id) 
    </td> 
</tr> 
+0

Darin Dimitrov,感謝您的建議。爲什麼我們需要MyViewModel.cshtml上的兩個ID? – Pingpong

+0

@Pingpong,一個是將其顯示爲文本,另一個顯示爲隱藏字段,以便在回發時將其發送到服務器,以便正確填充視圖模型。 –

+0

謝謝你的建議。有用。如果從控制器傳遞給查看的數據是包含集合的自定義類型,該怎麼辦?謝謝! – Pingpong

2

看看scott hanselman發佈的this。有模型綁定到字典,列表等示例