正常情况下,动作器中返回的字符串会在编码后再打印到html页面上,比如当动作器内容如下时:
public ActionResult test()
{
string res = "<input type='text' />";
return View((object)res);
}
会在页面中打印内容:
这是由动作器自行编码的,是动作器的一种自动保护措施。
但根据实际情况,有时也会有需要取消这种保护措施的情况出现。若要取消这种保护措施,动作器内容应如下所示:
public MvcHtmlString test()
{
string res = "<input type='text' />";
return new MvcHtmlString(res);
}
此时页面中打印的内容如下:
当遇到需要同时有编码与非编码部分时,可以使用编码方法对指定的字符串进行编码,此时动作器内容如下:
public ActionResult test()
{
string res = "<input type='text' />";
return View((object)res);
}
编码字符串时需要扩展方法的辅助,这里定义扩展方法如下:
namespace demo1.Infrastructure
{
public static class myExtend
{
public static MvcHtmlString MyEncode(this HtmlHelper html, string msg)
{
return new MvcHtmlString(html.Encode(msg)+msg);
}
}
}
然后html页面的代码如下:
@using demo1.Infrastructure
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>test</title>
</head>
<body>
<div>
@Html.MyEncode((string)Model)
</div>
</body>
</html>
最后的输出如下: