2011-07-28 6 views
3

ラベルとチェックボックスのリストを表示するビューを定義したい場合、ユーザーはチェックボックスを変更してからポストバックできます。私は辞書をポストバックするのに問題があります。つまり、postメソッドのdictionaryパラメータは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

これには辞書を使用しないでください。モデルバインドではうまく機能しません。ピタかもしれない。

ビューモデルがより適切であろう。

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

ダーリンディミトロフ、ご助言ありがとうございます。 MyViewModel.cshtmlに2つのIDが必要なのはなぜですか? – Pingpong

+0

@ Pingpong、1つはテキストとして表示し、もう1つは隠しフィールドとして表示するので、ポストバック時にサーバーに送信され、ビューモデルが正しく埋められます。 –

+0

ありがとうございました。できます。コントローラから表示するために渡されたデータが、コレクションを含むカスタムタイプの場合はどうなりますか?ありがとう! – Pingpong

2

scott hanselmanの投稿を参照してください。this投稿辞書、リストなどへのモデルバインディングの例があります

関連する問題