如何使用MVC3 Razor从视图包中呈现HTML

时间:2021-11-13 21:07:11

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.:

这将在HTML中呈现myas文本,即:

 &lt;type="hidden" name="example" value="examplevalue"&gt; 

So my question is how do I get Razor to do the equivalent of older:

所以我的问题是,我如何让剃刀做和老剃刀一样的事情:

<%= myData %>

and not replace the <>

不替换<>

Thanks Paul

谢谢你保罗

2 个解决方案

#1


159  

Use @Html.Raw(ViewBag.Mydata).

使用@Html.Raw(ViewBag.Mydata)。

#2


20  

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。

#1


159  

Use @Html.Raw(ViewBag.Mydata).

使用@Html.Raw(ViewBag.Mydata)。

#2


20  

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。