2011-12-07 50 views
2

我已经有了一个模型3个属性是类型的类型KeyValuePair <字符串,字符串>的属性定制MVC3的模板或HTML帮助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> 

感谢您的任何意见和建议。

+1

你的看法是什么叫你的模板? –

回答

2

您应该能够使用UIHint Property在模型中指定你想使用,例如其中DisplayTemplate:

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

这将参考DisplayTemplate查看名为“NameOfYourDisplayTemplate”,渲染时myProperty的。

+0

这对我有效。感谢Rionmonster –

1

在你TestModel类装饰MyProperty属性与数据类型属性,例如:

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

,然后创建为~/Views/Shared/DisplayTemplates/KeyValuePair.cshtml