Pages

Monday, November 21, 2011

MVC Tips #1, Passing HTML or Javascript as Data


Sometimes you need to render an html to output which the source of HTML is from your model. For security reasons rendering html directly from data requires to be explicitly requested, here is the 2 scenarios for doing so:

[AllowHtml]
If your model has a property which contains HTML content you add the AllowHtml property before the property. By doing so you inform the MVC that you expect html content in that property.
Although the it is named AllowHtml it also works for JavaScript.

@Html.Raw(Model.HtmlContent)
When rendering a Razor view to allow html content be rendered to output use @Html.Raw(Model.HtmlContent).

WARNING By using any of the above technique you need to make sure that the HTML or JavaScript content is safe. So if the data comes from some untrusted source you application will become vulnerable to attacks.

WARNING 2 Also pay attention to fact that AllowHtml also allows JavaScript, so dont assume that by applying this attribute only safe html code will be passed to client.


Note :
If you have a custom model binder and use pass the html values in your model, you may receive this exception:
A potentially dangerous Request.Form value was detected from the client
I found a solution for this problem at this Martijn Boland's blog post. which worked fine for me and you can learn about why this problem exists and how the solution works.

1 comment:

  1. Html.Raw doesn't seem to be working this way when using the viewbag.

    ReplyDelete