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

前端 未结 7 1787
佛祖请我去吃肉
佛祖请我去吃肉 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:09

    Here's naspinski solution with the ability to add htmlAttributes.

        public static MvcHtmlString DisplayWithIdFor(this HtmlHelper helper, Expression> expression, object htmlAttributes, string wrapperTag = "div")
        {
            var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
    
            if (htmlAttributes != null)
            {
                var tag = new TagBuilder(wrapperTag);
                tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) as IDictionary);
                tag.Attributes.Add("id", id);
                tag.SetInnerText(helper.DisplayFor(expression).ToHtmlString());
    
                return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
            }
            else
            {
                return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}", wrapperTag, id, helper.DisplayFor(expression)));
            }
        }
    

提交回复
热议问题