MVC2: Is there an Html Helper for raw Html?

后端 未结 4 855
孤街浪徒
孤街浪徒 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: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("", "", "None");
    
    
            Dictionary 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(
                    "", 
                    account.Key, 
                    account.Value,
                    selected == account.Key ? " selected='selected' " : ""
                );
    
            return new MvcHtmlString(tb.ToString());
        }
    

提交回复
热议问题