如何为KeyValuePair类型的属性创建自定义mvc模板或HTML助手?

本文关键字:string mvc 自定义 助手 HTML 创建 KeyValuePair 类型 属性 | 更新日期: 2023-09-27 18:17:22

我有一个模型,有3个属性类型为KeyValuePair

public class TestModel {
    public KeyValuePair<string,string> MyProperty{ get; set; }
}    

我的控制器代码如下,

 public ActionResult Index() {
     var model = new TestModel {MyProperty= new KeyValuePair<string, string>("Color", "Blue")};
     return View(model);
 }

如果我使用下面的Razor代码,我的结果不是我想要的。

@model TestModel
@Html.LabelFor(m => m.MyProperty)
@Html.DisplayFor(m => m.MyProperty)

我的视图最终呈现:

MyProperty关键颜色价值蓝色的

我想创建自己的帮助器或模板来覆盖此功能。我试图在Views'Shared'DisplayTemplates中创建一个自定义模板,如下所示,但它没有被选中。

@model KeyValuePair<string,string>
<label>This should show up</label>

感谢所有的评论和建议。

如何为KeyValuePair<string,string>类型的属性创建自定义mvc模板或HTML助手?

你应该能够在你的模型中使用UIHint属性来指定你想使用的DisplayTemplate,例如:

public class TestModel 
{
    [UIHint("NameOfYourDisplayTemplate")]
    public KeyValuePair<string,string> MyProperty{ get; set; }
}  

当呈现MyProperty时,这将指向名为"NameOfYourDisplayTemplate"的DisplayTemplate视图。

在您的TestModel类中,用DataType属性装饰MyProperty属性,例如:

[DataType("KeyValuePair")]
public class TestModel {
    public KeyValuePair<string,string> MyProperty{ get; set; }
}
然后创建您的视图为~/Views/Shared/DisplayTemplates/KeyValuePair.cshtml