Home >Backend Development >C++ >How to Properly Bind Dictionaries in ASP.NET MVC?

How to Properly Bind Dictionaries in ASP.NET MVC?

Linda Hamilton
Linda HamiltonOriginal
2025-01-10 07:20:43497browse

How to Properly Bind Dictionaries in ASP.NET MVC?

Binding dictionary values ​​in ASP.NET MVC is generally simple, but requires following specific syntax conventions for successful binding.

Model 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>

View tag

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.

Bind dictionary keys and values

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn