Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.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
C# 辅助程序无法正确渲染_C#_Asp.net Mvc 4_Razor 2 - Fatal编程技术网

C# 辅助程序无法正确渲染

C# 辅助程序无法正确渲染,c#,asp.net-mvc-4,razor-2,C#,Asp.net Mvc 4,Razor 2,我目前正在将我的aspx mvc视图迁移到razor引擎,但是当涉及到我的助手时,我遇到了一些麻烦 我不确定为什么,但是当我尝试在html扩展表单中使用帮助程序时,我的帮助程序是以文本而不是标记的形式呈现的,我得到的是文本而不是html 扩展代码为: public static string LinkButton(this HtmlHelper helper, string id, string value, string target, object htmlAttributes)

我目前正在将我的aspx mvc视图迁移到razor引擎,但是当涉及到我的助手时,我遇到了一些麻烦

我不确定为什么,但是当我尝试在html扩展表单中使用帮助程序时,我的帮助程序是以文本而不是标记的形式呈现的,我得到的是文本而不是html

扩展代码为:

    public static string LinkButton(this HtmlHelper helper, string id, string value, string target, object htmlAttributes)
    {
        var linkButton = new TagBuilder("div");
        var attributes = new RouteValueDictionary(htmlAttributes);

        linkButton.MergeAttribute("id", id);

        //-- apply the button class to the div and any other classes to the button
        linkButton.MergeAttribute("class", attributes.ContainsKey("class") ? string.Format("linkbutton {0}", attributes["class"]) : "linkbutton");

        var content = new TagBuilder("a");
        content.MergeAttribute("href", target);
        content.InnerHtml = value;

        linkButton.InnerHtml = content.ToString();
        return linkButton.ToString();
    }
这是一个非常简单的扩展,其用法如下:

[ul] @foreach (UpModule module in ViewBag.Modules) { [li]@Html.LinkButton(module.Name, module.Value, module.Target, new {@class = "landingButton"});[/li] } [/ul] [ul] @foreach(ViewBag.Modules中的UpModule模块) { [li]@Html.LinkButton(module.Name、module.Value、module.Target、new{@class=“landingButton”});[/li] } [/ul] 除了那些明显错误的html标签之外,我搞砸了什么

编辑
我应该注意到错误的标记在那里,因为我无法在我的问题中显示正确的标记,我完全知道它不会起作用。

@voroninp将返回类型从string切换到MvcHtmlString效果很好,在这种情况下,使用声明性帮助程序是一个更好、更清晰的选项,尽管为更复杂的帮助程序切换返回类型会更好。

模板中通过
@
razor语法返回的字符串默认为HTML编码,以便不直接输出HTML标记

var s = "<p>text</p>";
....
@s
为了防止这种情况,您可以使用
HtmlHelper
s
Raw
方法:

@Html.Raw(s)
或者您可以使用
HtmlString
(或.NET 4之前的
MvcHtmlString
):


你在写什么样的文件?我从未见过[ul]只用于
    的任何东西。你确定要它是string而不是MvcHtmlString吗?@Antarr Byrd标记在我的代码中是正确的,我要么头脑崩溃,无法正确地购买html标记,要么堆栈讨厌我now@voroninp这非常有效,但我不确定为什么Razor视图要求我使用MvcHtmlString。你能解释一下吗,因为我对此有点不知所措。@codejam为了防止跨站点脚本攻击(XSS),Razor将任何字符串编码为“html安全的”。但当Razor看到MvcHtmlstring时,它并没有将其编码。
    @Html.Raw(s)
    
    var s = new HtmlString("<p>text</p>");
    
    public static HtmlString LinkButton(this HtmlHelper helper, string id, string value, string target, object htmlAttributes)
    ...
    return new HtmlString(linkButton.ToString());