1

I have created a special User Control which inherits KeyValuePair. Inside my ViewModel, there is a property called lookup

[UIHint("Lookup")]
public KeyValuePair<string, string> lookup { get; set; }

User Control is

Html.TextBoxFor(m => m.Value, new { id = "Name", style = "width: 200px; background-color: #C0C0C0" })

Html.HiddenFor(m => m.Key, new { id="Guid"})

The user Control has some Jquery statements which set the value of the TextBox and the Hidden field.

When I do a DEBUG to the POST method of the Controller, I see no value inside the Lookup property?!

But If I changed the type of the property to string instead of KeyValuePair and also change the type of the User Control, I see a value.

I think I'm very close but I can't figure it out.

1 Answer 1

4

The KeyValuePair structure doesn't have a default parameterless constructor and can't be instantiated by the model binder. I recommend a custom model class for your view that has just those properties.

public class CustomControlViewModel
{
    public string Key { get; set; }
    public string Value { get; set; }
}

Transform your KVP into this model class for your view and/or use this class as the parameter on your action.

[HttpGet]
public ActionResult Lookup()
{
    return View( new CustomControlViewModel { Value = kvp.Value, Key = kvp.Key } );
}

[HttpPost]
public ActionResult Lookup( CustomControlViewModel lookup )
{
     ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, that's exactly what I want.
Why it doesn't work if it works properly using Dictionary, that implements <IEnumerable<KeyValuePair<TKey,TValue>> ?
@MarioLevrero I assume (without checking) that the model binder for a dictionary uses the Add method to update the dictionary.

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.