开发者

How do I render HTML from the Viewbag using MVC3 Razor

开发者 https://www.devze.com 2023-04-13 00:02 出处:网络
I am trying to pass a form element into an MVC3 view by using the Viewbag and simply write the HTML to the page ...

I am trying to pass a form element into an MVC3 view by using the Viewbag and simply write the HTML to the page ...

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

 &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


Use @Html.Raw(ViewBag.Mydata).


This should do the job

 @Html.Raw((String)ViewBag.myData)

MSDN: This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.

You need to be careful with accepting and displaying un-encoded HTML.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号