Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MVC Html帮助程序未被解释_Html_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

MVC Html帮助程序未被解释

MVC Html帮助程序未被解释,html,asp.net-mvc,asp.net-mvc-4,Html,Asp.net Mvc,Asp.net Mvc 4,我在MVC5中试用了自定义HTML帮助程序,但它们没有在浏览器中被解释。它们以弦的形式出现 HTML助手类 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; public static class ImageHelper { public static string Ima

我在MVC5中试用了自定义HTML帮助程序,但它们没有在浏览器中被解释。它们以弦的形式出现

HTML助手类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

public static class ImageHelper
{
    public static string ImageLink(this HtmlHelper helper, string id, string imgSrc, string altText)
    {
        var builder = new TagBuilder("img");

        builder.GenerateId(id);

        builder.MergeAttribute("src", imgSrc);
        builder.MergeAttribute("alt", altText);

        return builder.ToString(TagRenderMode.SelfClosing);
    }
}
HTML视图

@Html.ImageLink("objStatus", "/images/circle-205-i.png", "status")
浏览器显示:

string "<img alt="status" id="objStatus" src="/images/circle-205-i.png" />"
字符串“”

F12将其显示为一个字符串,而不是解释为HTML

您的助手正在返回一个字符串,MVC Razor将该字符串编码为HTML。正确的方法是返回如下所示的MvcHtmlString:

public static MvcHtmlString ImageLink(this HtmlHelper helper, string id, string imgSrc, string altText)
{
    var builder = new TagBuilder("img");

    builder.GenerateId(id);

    builder.MergeAttribute("src", imgSrc);
    builder.MergeAttribute("alt", altText);

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

另一种方法是在视图中使用
Html.Raw
,但您必须在任何地方都这样做。我在这里只提到这一点,因为这是可能的,上面是首选的解决方案。

Thank you@DavidG已辞职,明天再回到这里。断然的。