سؤال

I'm currently in the process of migrating my aspx mvc views to the razor engine but I've run into a bit of a head scratcher when it comes to my helpers.

I'm uncertain as to why but my helpers are being rendered out in text instead of as markup when I attempt to use the helper in its html extension form I get text not html.

The code for the extension is:

    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();
    }

This is a pretty simple extension and its used as follows:

[ul]
    @foreach (UpModule module in ViewBag.Modules)
    {
        [li]@Html.LinkButton(module.Name, module.Value, module.Target, new {@class = "landingButton"});[/li]
    }
[/ul]

apart from the blatently wrong html tags what is it that I've messed up?

edit I should note that the incorrect markup is there as I'm unable to get the correct markup to show up in the my question and I am fully aware that it will not work.

هل كانت مفيدة؟

المحلول

Strings returned in your templates by means of the @ razor syntax are by default HTML encoded in order to not output HTML markup directly.

var s = "<p>text</p>";
....
@s

will output something similar to

&lt;p&gt;text&lt;/p&gt;

In order to prevent this, you could use HtmlHelpers Raw method:

@Html.Raw(s)

Or you may use a HtmlString (or before .NET 4, MvcHtmlString):

var s = new HtmlString("<p>text</p>");

By using a HtmlString (MvcHtmlString), razor knows not to HTML-encode the output string.


In your particular case you therefore either use @Html.Raw(Html.LinkButton(...)), or you change the output type of your helper extension:

public static HtmlString LinkButton(this HtmlHelper helper, string id, string value, string target, object htmlAttributes)
...
return new HtmlString(linkButton.ToString());

نصائح أخرى

@voroninp switching the return type from string to MvcHtmlString worked perfectly however, in this case using the declarative helper is a better clearer option though switching the return type for my more complex helper will work much better.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top