asp.net-mvcvalidationvalidate-request

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


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.


Solution

  • 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;}
     }