0

I was going to use declarative HTML helpers, but then found out that they have not been implemented in a release of MVC 3.

I'm trying to get old HTML helpers to work with the following code:

private static String GenerateSingleOptionHTML(Question q)
{    
    String ret = "";

    for(int i = 0; i < 3; i++)
    {
        ret += String.Format("<li><input type=\"radio\" id=\"Q" + i +"\" value=\"" + i + "\" name=\"Q" + i +"\" />" + q.Body + "</li>");
    }

    return ret;
}

Ignore the html and tag as they work fine. What I get in my view, is: " <li><input type="radio" id="Q0" value="0" name="Q0" />Body Question 1</li><li><input type="radio" id="Q1" value="1" name="Q1" />Body Question 1</li><li><input type="radio" id="Q2" value="2" name="Q2" />Body Question 1</li> " rather than formatted HTML.

Thank you

Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101

2 Answers2

3

David Neale is right, but in ASP.NET MVC 3 you should actually return an instance of HtmlString, not MvcHtmlString (both will work, though):

private static HtmlString GenerateSingleOptionHTML(Question q)
{    
    String ret = "";

    for(int i = 0; i < 3; i++)
    {
        ret += String.Format("<li><input type=\"radio\" id=\"Q" + i 
            +"\" value=\"" + i + "\" name=\"Q" + i +"\" />" + q.Body + "</li>");
    }

    return new HtmlString(ret);
}
Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101
  • Hi, are you sure about this? I have conversion exception: Error 1 Cannot implicitly convert type 'System.Web.HtmlString' to 'string' –  Apr 13 '11 at 14:20
  • @vkip - Sorry, fixed the code example: you actually need to set `HtmlString` as return type – Sergi Papaseit Apr 13 '11 at 14:22
2

You need to return an instance of MvcHtmlString. Your output string is getting encoded.

The MvcHtmlString object will be treated as already encoded during rendering (I assume you're using the <%: %> syntax instead of <%= %> to inject the HTML into the page).

return MvcHtmlString.Create(ret);
David Neale
  • 16,498
  • 6
  • 59
  • 85
  • That's great, thank you. I knew there was something wrong with format of the string, but it's always a pain to find Microsoft's solution to that problem. ANywya, thx –  Apr 13 '11 at 14:18
  • I'm using Razor's @ notation to inject the HTML into the page. –  Apr 13 '11 at 14:24
  • 1
    @vkip - in that case you don't need to worry about anything in the view. Razor view engine escapes everything by default; you actually only need take action when you want something *not* escaped (you'd use `@Html.Raw(html_in_here)` – Sergi Papaseit Apr 13 '11 at 14:28
  • 1
    Razor does the equivalent of `:` by default. You can use `@Html.Raw(myString)` to get around this as well. – David Neale Apr 13 '11 at 14:28