MVC 3 - HTML Helper

二次信任 提交于 2019-12-24 23:50:32

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5650671/mvc-3-html-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!