Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is POSTing a Dictionary to an .NET MVC action possible?

I have a form which contains a series of fields like:

<input type="text" name="User[123]" value="Alice" />
<input type="text" name="User[456]" value="Bob" />
...

Where the index of the User array (123 and 456) are ID's associated with the value. I'm trying to update these values in the controller. My thinking is that a Dictionary that maps ID to name would work, but creating the action like:

public void Save(Dictionary<string, string> user) {
    // ...
}

results in the user parameter being null.

So, is passing a Dictionary possible? or, is there another method to achieve this?

like image 356
Brenton Alker Avatar asked Apr 19 '10 23:04

Brenton Alker


People also ask

What is dictionary in ASP NET MVC?

Dictionary in . NET represents a collection of key/value pairs. In this tutorial, learn how to create a dictionary, add items to a dictionary, remove items from a dictionary, and other dictionary operations using C# and . NET. C# Dictionary class is a generic collection of keys and values pair of data.

What are actions in MVC?

Actions are the ultimate request destination in an MVC application and it uses the controller base class.


1 Answers

It's possible for lists, I'm sure it carries over for dictionaries as well. Read through Model Binding to a List by Phil Haack for some understanding on how list binding works.

You should be able to do this:

<input type="hidden" name="User.Index" value="123" />
<input type="text" name="User[123]" value="Alice" />

<input type="hidden" name="User.Index" value="456" />
<input type="text" name="User[456]" value="Bob" />
like image 168
womp Avatar answered Oct 21 '22 10:10

womp