如何使用 MVC3 Razor 从 Viewbag 呈现 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7756464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I render HTML from the Viewbag using MVC3 Razor
提问by Sunrise
I am trying to pass a form element into an MVC3 view by using the Viewbag and simply write the HTML to the page ...
我正在尝试使用 Viewbag 将表单元素传递到 MVC3 视图中,然后简单地将 HTML 写入页面......
In controller:
在控制器中:
ViewBag.myData = "<input type=""hidden"" name=""example"" value=""examplevalue"">";
In view (I know I could use a helper for the form):
鉴于(我知道我可以使用表单的助手):
<form action="http://exampleurl/examplepage" method="post" id="example-form">
@ViewBag.myData
<input type="hidden" name="anotherexample" value="anotherexamplevalue" />
</form>
This renders the myData as text in the HTML i.e.:
这将 myData 呈现为 HTML 中的文本,即:
<type="hidden" name="example" value="examplevalue">
So my question is how do I get Razor to do the equivalent of older:
所以我的问题是如何让 Razor 做相当于更老的事情:
<%= myData %>
and not replace the <>
而不是替换 <>
Thanks Paul
谢谢保罗
回答by Yngve B-Nilsen
Use @Html.Raw(ViewBag.Mydata)
.
使用@Html.Raw(ViewBag.Mydata)
.
回答by Sunrise
This should do the job
这应该可以完成工作
@Html.Raw((String)ViewBag.myData)
MSDN: This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
MSDN:此方法使用 IHtmlString 类包装 HTML 标记,该类呈现未编码的 HTML。
You need to be careful with accepting and displaying un-encoded HTML.
您需要小心接受和显示未编码的 HTML。