除了EditorTemplate MVC之外,还有其他htmlAttributes 5.2

问题描述:

我正在使用EditorTemplate进行本地化显示DateTimeOffset。除了EditorTemplate MVC之外,还有其他htmlAttributes 5.2

EditorTemplate:

@model DateTimeOffset? 
@Html.TextBox("", (Model.HasValue ? Model.Value.ToLocalTime() 
    .ToString("yyyy-MM-dd HH:mm") : string.Empty), new 
    { 
     @class = "form-control datetimepicker" 
    }) 

这是正常工作时,我使用了Html.EditorFor。但是,我想将附加 htmlAttributes传递给我的视图中的对象。

查看:

@Html.EditorFor(model => model.ValidToDate, new { 
    htmlAttributes = new { @data_date_min_date = DateTime.Now.ToString() } 
}) 

本例中的属性(data_date_min_date)没有得到呈现。我如何提供额外的htmlAttributes到特定视图的特定字段?

您正通过ViewData字典传递此附加数据。 Html.EditorForoverloadadditionalData参数需要一个匿名对象,该对象将被合并到视图数据字典中。所以,你可能在你的编辑模板/视图数据字典局部视图

@Html.EditorFor(model => model.ValidToDate, 
            new { data_date_min_date = DateTime.Now.ToString()}) 

,并在编辑器中的模板

@model DateTimeOffset? 

<h4>Value passed from main view : @ViewData["data_date_min_date"]</h4> 

@Html.TextBox("", (Model.HasValue ? Model.Value.ToLocalTime() 
    .ToString("yyyy-MM-dd HH:mm") : string.Empty), new 
    { 
     @class = "form-control datetimepicker" 
    }) 
+0

'@ViewData [“data_date_min_date”]'不存在。它存储在@ @ ViewData [“htmlAttributes”]中。 – Sven

+0

不可以。如果您按照我在答案中显示的方式传递'data_date_min_date'的值,它应该可以工作。您将传递一个包含键和值的对象。但是你试图传递一个有另一个对象的对象。我在我的机器上验证了这一点,它完全有效。 – Shyju

作为一个完整的回答我的问题阅读:

htmlAttributes这在视图中定义的都传递到ViewData["htmlAttributes"]对象的EditorTemplate中。您可以通过这个入Html.TextBox直接,或提供额外的htmlAttributes为我做的:

@model DateTimeOffset? 
@{ 
    RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]); 
    string additionalHtmlAttributes = "form-control datetimepicker"; 
    if (htmlAttributes.ContainsKey("class")) 
    { 
     htmlAttributes["class"] = String.Format("{0} {1}", htmlAttributes["class"], additionalHtmlAttributes); 
    }else 
    { 
     htmlAttributes.Add("class", additionalHtmlAttributes); 
    } 
} 
@Html.TextBox("", (Model.HasValue ? Model.Value.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : string.Empty), htmlAttributes)