是否可以在viewmodel中使用一个属性来指定razor渲染没有html编码的字符串?
编辑:我问的是,是否可以在模型中添加属性并修改数据表示(就像你可以添加[Disable],[Layout(...)],[必需] ]等等 - 以这种方式使得html在字符串中呈现。
答案 0 :(得分:1)
我不知道,但似乎您可以将数据类型从字符串更改为HTMLString。如果您使用HTMlString,它应该在字符串中呈现HTML。
请参阅Always output raw HTML using MVC3 and Razor
该线程中的第二个响应显示了使用属性显示原始html的可能方式。
答案 1 :(得分:1)
尝试Html.Raw(yourstring)
这应该有所帮助。
答案 2 :(得分:0)
MVC默认情况下将字符串输出为纯字符串,而不是HTML。
e.g。在Action
:
public ActionResult Test()
{
var model = new TestViewModel(); // your view model
model.Message = "<b>hello</b>";
return View(model);
}
您的View
:
@model MyProject.TestViewModel
<div>
@Model.Message
</div>
这将呈现为:
<b>hello</b>
如果您想将其实际呈现为HTML,则需要将上述内容更改为:
@MvcHtmlString.Create(Model.Message)
或者,您可以创建一个扩展程序以使其更好:
public static MvcHtmlString ToMvcHtmlString(this String str)
{
if (string.IsNullOrEmpty(str))
return MvcHtmlString.Empty;
else
return MvcHtmlString.Create(str);
}
然后,在View
中将字符串呈现为HTML,您可以写:
@Model.Message.ToMvcHtmlString()
如果这不是你想要的,那么你应该向我们提供你的代码落伍的例子。