【问题标题】:can I use AdditionalMetadata with editor template in mvc3?我可以在 mvc3 中使用 AdditionalMetadata 和编辑器模板吗?
【发布时间】:2012-09-20 13:04:36
【问题描述】:

我需要为不同类型的数据创建一个编辑器模板,例如:对于字符串,我需要一个用于 largeString 和 shortstring 的 EditorTemplate

我发现对我来说最好的方法是使用编辑器模板。那么我可以使用 AdditionalMetadata 吗?对于这样的事情?

 [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" })
}

我可以这样做还是只为 stringLarge 和 StringShort 创建单独的 EditorTemplate?

【问题讨论】:

    标签: asp.net-mvc-3 asp.net-mvc-4


    【解决方案1】:

    您可以通过编写实现IMetadataAware 接口的自定义属性来做到这一点:

    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
    {
        ...
    }
    

    【讨论】:

    【解决方案2】:

    使用[附加元数据]

    视图模型:

     [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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多