Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

Rabbi picture Rabbi · Sep 1, 2010 · Viewed 107k times · Source

How can I allow a user to input HTML into a particular field using ASP.net MVC.

I have a long form with many fields that get mapped to this complex object in the controller.

I would like to make one field (the description) allow HTML which I will preform my own sanitation on at a later point.

Answer

Kelsey picture Kelsey · Sep 1, 2010

Add the following attribute the action (post) in the controller that you want to allow HTML for:

[ValidateInput(false)] 

Edit: As per Charlino comments:

In your web.config set the validation mode used. See MSDN:

<httpRuntime requestValidationMode="2.0" />

Edit Sept 2014: As per sprinter252 comments:

You should now use the [AllowHtml] attribute. See below from MSDN:

For ASP.NET MVC 3 applications, when you need to post HTML back to your model, don’t use ValidateInput(false) to turn off Request Validation. Simply add [AllowHtml] to your model property, like so:

public class BlogEntry {
    public int UserId {get;set;}
    [AllowHtml] 
    public string BlogText {get;set;}
 }