Asp.net mvc 3 我可以在mvc3中将附加元数据与编辑器模板一起使用吗?
我需要为不同类型的数据创建一个编辑器模板,例如:对于字符串,我需要一个EditorTemplate用于largeString和shortstring 我发现对我来说最好的方法是使用编辑器模板。那么我可以使用额外的元数据吗?像这样的东西Asp.net mvc 3 我可以在mvc3中将附加元数据与编辑器模板一起使用吗?,asp.net-mvc-3,asp.net-mvc-4,Asp.net Mvc 3,Asp.net Mvc 4,我需要为不同类型的数据创建一个编辑器模板,例如:对于字符串,我需要一个EditorTemplate用于largeString和shortstring 我发现对我来说最好的方法是使用编辑器模板。那么我可以使用额外的元数据吗?像这样的东西 [UIHint("StringLarge")] [AdditionalMetadata("width", "50px")] public DateTime Date { get; set; } 我的编辑器模板StringLarge.cshtml
[UIHint("StringLarge")]
[AdditionalMetadata("width", "50px")]
public DateTime Date { get; set; }
我的编辑器模板StringLarge.cshtml
@inherits System.Web.Mvc.WebViewPage<System.String>
if("have AdditionalMetadata"){
@Html.TextBox("", Model, new { @class = "StringLarge" })
}
else
{
@Html.TextBox("", Model, new { @class = "StringShort" })
}
@继承System.Web.Mvc.WebViewPage
如果(“有额外的元数据”){
@TextBox(“,Model,new{@class=“StringLarge”})
}
其他的
{
@TextBox(“,Model,new{@class=“StringShort”})
}
我可以为stringLarge和StringShort创建separtes EditorTemplate吗?您可以通过编写实现接口的自定义属性来实现这一点:
public class MyStringsAttribute : Attribute, IMetadataAware
{
private readonly string _value;
public MyStringsAttribute(string value)
{
_value = value;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.TemplateHint = "Strings";
metadata.AdditionalValues["someKey"] = _value;
}
}
然后:
[MyStrings("somevalue")]
public DateTime Date { get; set; }
最后,在自定义编辑器模板(~/Views/Shared/EditorTemplates/Strings.cshtml
)中,您可以检查是否存在此附加元数据:
@{
var additionalMetadata = (string)ViewData.ModelMetadata.AdditionalValues["someKey"];
}
@if (string.Equals(additionalMetadata, "somevalue"))
{
...
}
else
{
...
}
使用[附加元数据] 视图模型:
[UIHint("StringCorto")]
[AdditionalMetadata("style", "width:100px")]
public string Nit { get; set; }
编辑器模板:
@inherits System.Web.Mvc.WebViewPage<System.String>
@{
this.ViewData.ModelMetadata.AdditionalValues.Add("class", "StringCorto");
}
@Html.TextBox(string.Empty, ViewContext.ViewData.TemplateInfo.FormattedModelValue, this.ViewData.ModelMetadata.AdditionalValues)
@继承System.Web.Mvc.WebViewPage
@{
this.ViewData.ModelMetadata.AdditionalValues.Add(“class”,“StringCorto”);
}
@TextBox(string.Empty、ViewContext.ViewData.TemplateInfo.FormattedModelValue、this.ViewData.ModelMetadata.AdditionalValues)
就像这里一样,对吗?我认为它可能会更简单,就像您在javascript Yeap中所做的那样,实现IMetadataAware
是实现这一点的一种方法,或者使用[AdditionalMetadata]
属性。这真的取决于你决定哪种方法更适合你。