Branislav B.
Branislav B.

Reputation: 557

ASP.NET MVC3 RAZOR Helpers returning plain text

this is my code in the helper class

    public static string GenerateMenu(this HtmlHelper helper)
    {
        var items = GetAllMenuItems();
        bool isIndex = false;
        var currentUrl = HttpContext.Current.Request.Url;
        StringBuilder menu = new StringBuilder();

        if (currentUrl.AbsolutePath == "/")
        {
            isIndex = true;
        }

        menu.AppendLine("<ul class=\"layout-menu\">");

        foreach (var item in items)
        {
            menu.Append("<li><a ");
            if (isIndex)
            {
                if (items.First() == item)
                {
                    menu.Append("class=\"menuItemSelected\" ");
                }
            }
            if(currentUrl.AbsolutePath.ToLower().Contains(item.NavigateURL.ToLower()))
            {
                menu.Append("class=\"menuItemSelected\" ");
            }
            menu.Append("href=\"" + item.NavigateURL + "\">");
            menu.Append(item.Text);
            menu.Append("</a></li>" + Environment.NewLine);
        }
        menu.AppendLine("</ul>"); 

        return menu.ToString();
    }

Im displaying it using

@Html.GenerateMenu()

It renders it perfectly but not as functional objects but only as plain text, any help ?

Thanks

Upvotes: 2

Views: 1212

Answers (3)

Rafay
Rafay

Reputation: 31043

since you are using mvc3 you can use the HtmlString

public static HtmlString GenerateMenu(this HtmlHelper helper)
    {
        /*
          your code here 
        */ 

        return new HtmlString(menu.ToString());

    }

Upvotes: 3

Arie van Someren
Arie van Someren

Reputation: 457

I would suggest :

 public static MvcHtmlString GenerateMenu(this HtmlHelper helper)
 {
     ....
     return new MvcHtmlString(menu.ToString());
 }

Upvotes: 1

Lucas Lopes
Lucas Lopes

Reputation: 86

Change your return type to MvcHtmlString and return a new MvcHtmlString(menu.ToString());

Upvotes: 1

Related Questions