Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Binding to a dictionary

I'm trying to bind dictionary values within MVC.

Within the action I have:

model.Params = new Dictionary<string, string>();  model.Params.Add("Value1", "1"); model.Params.Add("Value2", "2"); model.Params.Add("Value3", "3"); 

and within the view I have:

@foreach (KeyValuePair<string, string> kvp in Model.Params) {  <tr>   <td>     <input type="hidden" name="Params.Key" value="@kvp.Key" />     @Html.TextBox("Params[" + kvp.Key + "]")   </td> </tr> } 

But the view doesn't display the initial values, and when the form is submitted the Params property is null?

like image 606
user644344 Avatar asked Mar 04 '11 08:03

user644344


People also ask

What is binding in ASP NET MVC?

What Is Model Binding? ASP.NET MVC model binding allows mapping HTTP request data with a model. It is the procedure of creating . NET objects using the data sent by the browser in an HTTP request. Model binding is a well-designed bridge between the HTTP request and the C# action methods.

What is dictionary in ASP NET MVC?

In C#, Dictionary is used to store the key-value pairs. The Dictionary is the same as the non-generic hashtable. It can be defined under System. Collection. Generic namespace.

How do I bind a model to view in MVC core?

How does model binding work in ASP.NET Core MVC. In an empty project, change Startup class to add services and middleware for MVC. Add the following code to HomeController, demonstrating binding of simple types. Add the following code to HomeController, demonstrating binding of complex types.

What is bind property in C#?

The Binding class is used to bind a property of a control with the property of an object. For creating a Binding object, the developer must specify the property of the control, the data source, and the table field to which the given property will be bound.


1 Answers

In ASP.NET MVC 4, the default model binder will bind dictionaries using the typical dictionary indexer syntax property[key].

If you have a Dictionary<string, string> in your model, you can now bind back to it directly with the following markup:

<input type="hidden" name="MyDictionary[MyKey]" value="MyValue" /> 

For example, if you want to use a set of checkboxes to select a subset of a dictionary's elements and bind back to the same property, you can do the following:

@foreach(var kvp in Model.MyDictionary) {     <input type="checkbox" name="@("MyDictionary[" + kvp.Key + "]")"         value="@kvp.Value" /> } 
like image 154
Ant P Avatar answered Sep 21 '22 13:09

Ant P