MVC2: Is there an Html Helper for raw Html?

后端 未结 4 856
孤街浪徒
孤街浪徒 2021-01-13 13:43

Is there an Html helper that simply accepts and returns raw html? Rather than do something ugly like this:

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

        
相关标签:
4条回答
  • 2021-01-13 14:11

    There is such helper now:

    Html.Raw("<h2>Results</h2>")
    
    0 讨论(0)
  • 2021-01-13 14:14

    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.

    0 讨论(0)
  • 2021-01-13 14:30

    For MVC2:

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

    Found here:

    store and display html tags in MVC

    0 讨论(0)
  • 2021-01-13 14:31

    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 讨论(0)
提交回复
热议问题