2010-12-05 13 views
6

コントローラの動作方法でDictionary<string, double?>がビューに渡されます。私は、私の見解では、以下があります。モデルを辞書にバインドする

以下
<% foreach (var item in Model.Items) { %> 
<%: Html.Label(item.Key, item.Key)%> 
<%: Html.TextBox(item.Key, item.Value)%> 
<% } %> 

はPOST操作を処理する私のアクションメソッドです:

[HttpPost] 
public virtual ActionResult MyMethod(Dictionary<string, double?> items) 
{ 
    // do stuff........ 
    return View(); 
} 

私はPOSTアクションをテキストボックスにいくつかの値を入力し、送信ボタンを押すとメソッドはアイテムを戻していないのですか?私は間違って何をしていますか?

答えて

9

辞書にバインドできるように、入力フィールドの名前付け方法についてはthis blog postとお読みください。

<input type="hidden" name="items[0].Key" value="key1" /> 
<input type="text" name="items[0].Value" value="15.4" /> 
<input type="hidden" name="items[1].Key" value="key2" /> 
<input type="text" name="items[1].Value" value="17.8" /> 

線に沿って何かを生成することができます:あなたはキーの追加の隠しフィールドが必要になります。これは言われて

<% var index = 0; %> 
<% foreach (var key in Model.Keys) { %> 
    <%: Html.Hidden("items[" + index + "].Key", key) %> 
    <%: Html.TextBox("items[" + index +"].Value", Model[key]) %> 
    <% index++; %> 
<% } %> 

を、個人的に私はあなたの中に辞書を使用していないあなたをお勧めします再生回数彼らは醜いですし、あなたは醜いコードを書く必要がモデルバインダーのための適切な名前を生成するために。私はビューモデルを使用します。ここでは例です:

モデル:

public class MyViewModel 
{ 
    public string Key { get; set; } 
    public double? Value { get; set; } 
} 

コントローラー:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new[] 
     { 
      new MyViewModel { Key = "key1", Value = 15.4 }, 
      new MyViewModel { Key = "key2", Value = 16.1 }, 
      new MyViewModel { Key = "key3", Value = 20 }, 
     }; 
     return View(model); 
    } 

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

ビュー(~/Views/Home/Index.aspx):

<% using (Html.BeginForm()) { %> 
    <%: Html.EditorForModel() %> 
    <input type="submit" value="OK" /> 
<% } %> 

エディタテンプレート(~/Views/Home/EditorTemplates/MyViewModel.ascx):

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<Models.MyViewModel>" %> 
<%: Html.HiddenFor(x => x.Key) %> 
<%: Html.TextBoxFor(x => x.Value) %> 
関連する問題