开发者

MVC 3 - HTML Helper

开发者 https://www.devze.com 2023-02-24 17:26 出处:网络
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 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><开发者_Go百科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


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);
}


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);
0

精彩评论

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