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.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
Anwar
  • 4,470
  • 4
  • 24
  • 30

1 Answers1

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 )
{
     ...
}
tvanfosson
  • 524,688
  • 99
  • 697
  • 795