问题
I've got 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 up rendering:
MyProperty Key Color Value Blue
I'd like to create my own helper or template to override this functionality. I attempted to create a custom template in the Views\Shared\DisplayTemplates as shown below, but it wasn't picked up.
@model KeyValuePair<string,string>
<label>This should show up</label>
Thanks for any and all comments/suggestion.
回答1:
You should be able to use the UIHint Property in your model to specify which DisplayTemplate you would like to use, for example:
public class TestModel
{
[UIHint("NameOfYourDisplayTemplate")]
public KeyValuePair<string,string> MyProperty{ get; set; }
}
This would refer to the DisplayTemplate View named "NameOfYourDisplayTemplate", when rendering MyProperty.
回答2:
In your TestModel
class decorate the MyProperty
property with DataType 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
来源:https://stackoverflow.com/questions/8419484/how-can-i-create-a-custom-mvc3-template-or-html-helper-for-a-property-of-type-ke