Binding dictionary values in ASP.NET MVC is generally simple, but requires following specific syntax conventions for successful binding.
In the model class, you should define the dictionary attribute and initialize it with the value:
<code class="language-csharp">public class MyModel { public Dictionary<string, string> Params { get; set; } public MyModel() { Params = new Dictionary<string, string>(); Params.Add("Value1", "1"); Params.Add("Value2", "2"); Params.Add("Value3", "3"); } }</code>
In a view, bind to dictionary keys and values using the following syntax:
<code class="language-html">@foreach (KeyValuePair<string, string> kvp in Model.Params) { <tr><td> @Html.TextBox("Params[" + kvp.Key + "]") </td> </tr> }</code>
This syntax ensures that the name attribute structure of each input field is "Params[key]", matching the indexer syntax used in model binding.
In ASP.NET MVC 4, the default model binder binds dictionaries using the typical dictionary indexer syntax (property[key]). Therefore, the following tag will be successfully bound to Dictionary<string, string>
:
<code class="language-html">@foreach (var kvp in Model.MyDictionary) { <input type="checkbox" name="@string.Format("MyDictionary[{0}]", kvp.Key)" checked="@kvp.Value" /> }</code>
This allows you to bind checkboxes to dictionary elements. Note that checked="@kvp.Value"
assumes that kvp.Value
is a boolean. If kvp.Value
is a string, this part of the code needs to be adjusted according to the actual situation, such as using checked="@(kvp.Value == "true")"
.
The above is the detailed content of How to Properly Bind Dictionaries in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!