Paweł Reszka
Paweł Reszka

Reputation: 1557

Dynamic Form in ASP.NET MVC3 Razor

I have a small problem. I want to have dropdown list with some objects. After clicking on one I want to add it to list with textfield for naming it. I don't want to limit quantity of this fields. I want to receive in controller ID (stored in dropdown list) and name (given by user) for each selected item. How can I do it? I was thinking about storing it in some fields as a text, and parsing in cotroller but I think it's not elegant.

EDIT. Ok, Thansk for your help, but it's not working for me correctly. I generate html like this:

<input type="hidden" value="96" name="Inputs[0].Key">
<input type="text" name="Inputs[0].Value">

In my controller I'm receiving this dictionary. The problem is that quantity of elements is correct, but all values are null. What is wrong here?

Upvotes: 0

Views: 244

Answers (2)

Retired_User
Retired_User

Reputation: 1595

Use IEnumerable<KeyPairValue<string,string>> MySelectedItem = new List<KeyPairValue<string,string>>(); on model, and when adding it to the list, name it like an array:

MySelectedItem[1].Key, MySelectedItem[1].Value, MySelectedItem[2].Key...

(I haven't tested this, but it should work)

Edit: check out this blog post with better explanation on how to do it: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Upvotes: 1

Levi Botelho
Levi Botelho

Reputation: 25194

The best way to go about this is by using array-style model binding.

So, for each element you wish to name you create a hidden field to store the drop down value plus a text field to store the user-given name. You name them as follows:

<input type="hidden" name="element[0].Key" /><input type="text" name="name[0].Value" />

increasing the index value each time. This is easily achieved with a bit of JavaScript. You then create an action method which takes a KeyValuePair<string, string>[] as a parameter. You will then be able to parse through your values no problem with a loop or LINQ expression.

Upvotes: 1

Related Questions