How can I create a custom MVC3 template or HTML helper for a property of type KeyValuePair<string,string>

谁都会走 提交于 2019-12-10 22:57:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!