开发者

MVC2: Is there an Html Helper for raw Html?

开发者 https://www.devze.com 2022-12-18 09:25 出处:网络
Is there an Html helper that simply accepts and returns raw html? Rathe开发者_高级运维r than do something ugly like this:

Is there an Html helper that simply accepts and returns raw html? Rathe开发者_高级运维r than do something ugly like this:

<% if (Model.Results.Count > 0) { %><h2>Results</h2><% } %>

I'd like to do something like this:

 <% if (Model.Results.Count > 0) { Html.RawHtml("<h2>Results</h2>") } %>

Not a whole lot cleaner, but I think it's a bit of an improvement. Does something like that exist? Or is there perhaps a better alternative to output raw html from within those escape characters than using Html helpers?


For MVC2:

<%: MvcHtmlString.Create("<h2>Results</h2>") %>

Found here:

store and display html tags in MVC


Response.Write should work. (Although maybe it's kind of taking a step back!) You should be able to create an extension method to do it. And maybe instead of using HTML string, you might want to build your markup in code using the TagBuilder.


There is such helper now:

Html.Raw("<h2>Results</h2>")


If you want to use an HtmlHelper for whatever you're doing, you can return an MvcHtmlString built with a TabBuilder

Here an example of one that I use:

    public static MvcHtmlString AccountsDropDown(this HtmlHelper helper, string name,  object htmlAddributes = null, bool addNull = false, Guid? selected = null)
    {
        Account acc = HttpContext.Current.Session["account"] as Account;

        TagBuilder tb = new TagBuilder("select");

        tb.GenerateId(name);
        tb.Attributes["name"] = name;

        if (addNull)
            tb.InnerHtml += string.Format("<option value= '{0}'> {1} </option>", "", "None");


        Dictionary<Guid, String> accounts;

        if (acc.Master)
            accounts = db.Account.ToDictionary(x => x.Id, x => x.Name);
        else
            accounts = db.Account.Where(x => x.Id == acc.Id).ToDictionary(x => x.Id, x => x.Name);

        foreach (var account in accounts)
            tb.InnerHtml += string.Format(
                "<option value= '{0}' {2}> {1} </option>", 
                account.Key, 
                account.Value,
                selected == account.Key ? " selected='selected' " : ""
            );

        return new MvcHtmlString(tb.ToString());
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消