MVC3 Html.DisplayFor — Is it possible to have this control generate an ID?

前端 未结 7 1775
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-08 17:16

I want to be able to display some text, but also have the text be modifiable via jQuery.

<%= Html.DisplayFor(model => model.DeviceComponentName)%>
         


        
7条回答
  •  广开言路
    2021-02-08 18:00

    To avoid 'magic string' inputs (in case your model properties change), you could do this with an extension. It also makes for much cleaner code:

    public static MvcHtmlString DisplayWithIdFor(this HtmlHelper helper, Expression> expression, string wrapperTag = "div")
    {
        var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
        return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}", wrapperTag, id, helper.DisplayFor(expression)));
    }
    

    Then simply use it like this:

    @Html.DisplayWithIdFor(x => x.Name)
    

    Will produce

    Bill

    Or if you want it to be wrapped in a span:

    @Html.DisplayWithIdFor(x => x.Name, "span")
    

    Which will make:

    Bill
    

    Non-Razor

    For non Razor syntax, you simply use it like this:

    <%= Html.DisplayWithIdFor(x => x.Name) %>
    

    and:

    <%= Html.DisplayWithIdFor(x => x.Name, "span") %>
    

提交回复
热议问题