ASP.NET MVC 3 Binds KeyValuePair User Controls to ViewModel

I created a special User Control that inherits KeyValuePair. In my ViewModel, there is a property called lookup

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

User management

 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 several Jquery statements that set the value of the TextBox and Hidden field.

When I do DEBUG for the controller's POST method, I don’t see the value inside the Lookup property ?!

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

I think I'm very close, but I can’t understand.

+1
asp.net-mvc-3 user-controls
source share
1 answer

The KeyValuePair structure KeyValuePair not have a constructor without default parameters and cannot be instantiated by the model. I recommend a custom model class for your view, which has only those properties.

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

Convert your KVP to this model class for your presentation and / or use this class as a parameter of your action.

 [HttpGet] public ActionResult Lookup() { return View( new CustomControlViewModel { Value = kvp.Value, Key = kvp.Key } ); } [HttpPost] public ActionResult Lookup( CustomControlViewModel lookup ) { ... } 
+4
source share

All Articles