首页 > 解决方案 > 在创建自定义图像 Html 帮助程序时,它会抛出 System.ArgumentNullException: 'Value cannot be null。参数名称:virtualPath'

问题描述

在创建自定义图像 Html Helper 时它会抛出

“System.ArgumentNullException:'值不能为空。参数名称:virtualPath'”

public static IHtmlString Image(this HtmlHelper helper, string src, string alt, string height, string width, params string[] allClasses)
{
    TagBuilder tb = new TagBuilder("img");
    tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));//throws error
    tb.Attributes.Add("alt", alt);
    if (!string.IsNullOrEmpty(height) || !string.IsNullOrEmpty(width))
    {
        StringBuilder value = new StringBuilder();

        if (!string.IsNullOrEmpty(height))
            value.AppendFormat("height:{0};", height);

        if (!string.IsNullOrEmpty(width))
            value.AppendFormat("width:{0};", width);

        tb.Attributes.Add("style", value.ToString());
    }
    if (allClasses?.Any() ?? false)
        tb.Attributes.Add("class", string.Join(" ", allClasses));

    return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}

标签: c#asp.net-mvc

解决方案


推荐阅读