0

I have a weird problem.

I'm making dynamic form in Razor. I'm using dictionary to store dynamically added inputs. I generate code like that:

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

I receive in my controller this dictionary. It always has as many elements that I added, but all of them are empty.

This is part of my model:

public class MetriceModelTaskSchedule
{
     public IEnumerable<KeyValuePair<long, string>> Inputs { get; set; }
}

What can be wrong here?

2
  • Perhaps you have missed get the code? Commented Feb 18, 2013 at 15:26
  • ok, now I can see the code. Commented Feb 18, 2013 at 15:28

1 Answer 1

3

What can be wrong here?

The fact that the KeyValuePair<TKey, TValue> class has the Key and Value properties which are readonly. They do not have a setter meaning that the model binder simply cannot set their value.

So as always start by defining a view model:

public class InputViewModel
{
    public long Key { get; set; }
    public string Value { get; set; }
}

and then:

public class MetriceModelTaskSchedule
{
    public IEnumerable<InputViewModel> Inputs { get; set; }
}

Alternatively you could use a Dictionary:

public class MetriceModelTaskSchedule
{
    public IDictionary<long, string> Inputs { get; set; }
}

Also make sure that you have respected the standard naming convention for your input fields in the view so that the model binder can successfully bind them to your model:

<div>
    <input type="text" name="Inputs[0].Key" value="1" />
    <input type="text" name="Inputs[0].Value" value="value 1" />
</div>
<div>
    <input type="text" name="Inputs[1].Key" value="2" />
    <input type="text" name="Inputs[1].Value" value="value 2" />
</div>
...
Sign up to request clarification or add additional context in comments.

3 Comments

I did as you wrote (I added additional model) and I still have 0 for every Key and null for every Value.
Then you probably didn't respect the naming convention for your input fields. Please read the article I have linked to in my answer and make sure that your input fields are named accordingly when you inspect the HTML of your page.
Oh, yeah, it was that. I was doing it correctly, but when I was searching for mistakes I made another mistake. Thank you for your help!

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.