Passing HTML Attributes and [DisplayFormat] using Html.EditorFor and Html.TextBox

杀马特。学长 韩版系。学妹 提交于 2019-12-11 02:28:38

问题


I am trying to use Html.EditorFor for a value where I need both a DisplayFormat attribute and an HTML attribute (specfically a CSS class) to be applied.

Html.TextBox ignores the DisplayFormat attribute, and Html.EditorFor will not let me pass Html attributes. Other than writing the HTML myself, what is the preferred solution here?


回答1:


Here's one possibility:

public class MyModel
{
    [UIHint("MyDateTemplate")]
    public DateTime Value { get; set; }
}

and in ~/Views/Home/EditorTemplates/MyDateTemplate.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%: Html.TextBox(
    string.Empty, 
    Model.ToString("dd/MM/yyyy"), 
    new { @class = "foo" }
)%>

and in the main view:

<%: Html.EditorForModel()

or yet another one:

public class MyModel
{
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Value { get; set; }
}

and in your main view:

<div class="foo">
    <%: Html.EditorFor(x => x.Value) %>
</div>

and in your css:

.foo input {
    /* define some rule here */
}



回答2:


I came across this same issue just now. If you are using an editor template for e.g. a date picker, you can simply do (using Razor):

@model System.DateTime
@Html.TextBox("", Model.ToString(ViewData.ModelMetadata.DisplayFormatString), new { @class = "date" })

That will format the date using the value from the DisplayFormat attribute.



来源:https://stackoverflow.com/questions/3927488/passing-html-attributes-and-displayformat-using-html-editorfor-and-html-textbo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!