1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| * **第三個範例,加入Img這個Tag** * ```csharp public static MvcHtmlString ImageFor_WithOriginData<TModel, TProp>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProp>> expression, object HtmlAttributes = null){ string value = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model == null ? "" : ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model.ToString(); //屬性的值 string propname = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName;
//透過AnonymousObjectToHtmlAttributes將HtmlAttribute讀取出來 var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(HtmlAttributes); attrs.Add("data-content", value); attrs.Add("src", value); attrs.Add("name", propname);
var img = new TagBuilder("img"); img.MergeAttributes(attrs); return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing)); }
|