0

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?

1
  • Answer for your edit: If you're using exactly the code you posted, you are missing close tags for input. You should do like this: <input type="hidden" value="96" name="Inputs[0].Key" /> or this <input type="hidden" value="96" name="Inputs[0].Key"></input> Commented Feb 18, 2013 at 16:14

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Answer for your edit: If you're using exactly the code you posted, you are missing close tags for input. You should do like this: <input type="hidden" value="96" name="Inputs[0].Key" /> or this <input type="hidden" value="96" name="Inputs[0].Key"></input>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.