How to create your own MVC3 template or HTML helper for a property of type KeyValuePair <string, string>
I have a model with 3 properties that are of type KeyValuePair
public class TestModel { public KeyValuePair<string,string> MyProperty{ get; set; } }
My controller code is as follows:
public ActionResult Index() { var model = new TestModel {MyProperty= new KeyValuePair<string, string>("Color", "Blue")}; return View(model); }
If I use the following Razor code, my results are not what I want.
@model TestModel @Html.LabelFor(m => m.MyProperty) @Html.DisplayFor(m => m.MyProperty)
My view ends with rendering:
MyProperty Key Color Cost Blue
I would like to create my own helper or template to override this functionality. I tried to create my own template in the \ Shared \ DisplayTemplates view, as shown below, but it was not raised.
@model KeyValuePair<string,string> <label>This should show up</label>
Thanks for any comments and suggestions.
You can use the UIHint Property in your model to indicate which DisplayTemplate you would like to use, for example:
public class TestModel { [UIHint("NameOfYourDisplayTemplate")] public KeyValuePair<string,string> MyProperty{ get; set; } }
This refers to a DisplayTemplate view named "NameOfYourDisplayTemplate" when rendering MyProperty.
In your TestModel
class, decorate the MyProperty
property with the MyProperty
attribute, for example:
[DataType("KeyValuePair")] public class TestModel { public KeyValuePair<string,string> MyProperty{ get; set; } }
and then create your view as ~/Views/Shared/DisplayTemplates/KeyValuePair.cshtml