Shravan Kumar Kasagoni

Skip Navigation
How to allow user to input html in ASP.NET MVC?

How to allow user to input html in ASP.NET MVC?

 /  1 response

Whenever we submit HTML or JavaScript as input in ASP.NET MVC application we get an exception like “A potentially dangerous Request.Form value was detected from the client (……)”. Because ASP.NET MVC has built-in request validation that helps you automatically protect against cross-site scripting (XSS) attacks and HTML injection attacks, it will prevent the user from posting HTML or JavaScript as input.

But sometime we want to explicitly disable request validation. We want to allow user to post html as input like, for example we have view which take the blog post as input from rich text editor, In ASP.NET MVC we have multiple options to disable request validation at various levels.

In ASP.NET MVC (V1, V2, V3) we can use [ValidateInput(false)] attribute, to disable request validation during model binding. We should add this attribute on top the action method in controller to which you are submitting input.

public ActionResult SaveBlogPost(BlogPost post)
    //logic for saving blogpost goes here
    return View();

[ValidateInput(false)] attribute disables request validation on complete model or view model, but we want to allow html on only few properties of model or view model, for example in BlogPost model class contains three properties Title, PostContent, List<Tag>.

Among three properties we want to allow html only for PostContent ,In ASP.NET MVC 3 we have granular control over request validation, ASP.NET MVC3 has built-in attribute to disable validation at property level. We can [AllowHtml] attribute on properties in model or view model to disable request validation.

public class BlogPost
    public string Title { get; set; }

    public string PostContent { get; set; }

    public List<Tag> Tags { get; set; }

[AllowHtml] attribute allows a request to include HTML mark-up during model binding by skipping request validation for the property.

Write a response

Your email address will not be published.

All code will be displayed literally.