Razor and HTML Helpers

前端 未结 4 1121
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 12:33

I\'m trying to port the old HTML.Image helper, that I\'m sure everyone has used at one point or another, and I\'m having issues. The following compiles fine:



        
4条回答
  •  鱼传尺愫
    2020-12-29 13:10

    I had the same problem and i had used MvcHtmlString as return type for these 2 extension method and it works

    public static class ImageHelper
    {
        public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
        {
            return Image(helper, id, url, alternateText, null);
        }
    
        public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText,
                                   object htmlAttributes)
        {
            var builder = new TagBuilder("img");
    
            builder.GenerateId(id);
    
            builder.MergeAttribute("alt", alternateText);
            builder.MergeAttribute("src",url);
    
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }
    

提交回复
热议问题