MVC3 HtmlHelper返回'

时间:2011-10-21 09:28:00

标签: asp.net-mvc-3 html-helper html-entities

如何让MVC3 Html助手返回一个非html编码的字符串?

以下方法:

    public static string SelectedIfEqual(this int id, int otherId)
    {

        if (id == otherId)
            return new MvcHtmlString(" selected='selected'").ToString();
        return null;  

    }

返回selected='selected'而不是selected='selected'

我甚至尝试过:

    return MvcHtmlString.Create(" selected='selected'").ToHtmlString();

但它返回相同的......: - (

2 个答案:

答案 0 :(得分:4)

返回HtmlString或将结果传递给Html.Raw()来电 将您的功能更改为:

public static MvcHtmlString SelectedIfEqual(this int id, int otherId)
{
  if (id == otherId)
    return new MvcHtmlString(" selected='selected'");
  return null;  
}

如果您不想更改代码,请将扩展名添加到HtmlHelper

public static class MyHelper
{
  // This doesn't work
  //public static Foo Grid(this HtmlHelper helper, string id)
  //{
  //  return new Foo(id).ToString();
  //}

  // This should work as intended
  public static MvcHtmlString Foo(this HtmlHelper helper, Foo theFoo)
  {
    return theFoo.ToHtmlString();
  }
}

在课程Foo中,ToHtmlString()方法看起来像

public MvcHtmlString ToHtmlString() 
{
  return new MvcHtmlString(ToString());
}

然后在视图中你可以使用

@Html.Foo(theFoo)

如果您不想使用Extension Helper,您可以选择:

@Html.Raw(Model.idField.SelectIfEqual(otherId))

希望这有帮助。

答案 1 :(得分:0)

或者,您可以创建一个不编码已添加的HTML属性的帮助程序类。

public class HtmlAttributeNoEncoding : System.Web.Util.HttpEncoder
{
    protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
    {
        output.Write(value);
    }
}
相关问题