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

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.

blogpost

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

blog

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

Sharavan Kumar Kasagoni

Shravan is working as Senior Development Engineer in Pramati Technologies, earlier he worked with Thomson Reuters. He is responsible for design and development of RESTful APIs, Single Page Web Applications. He is awarded as Microsoft Microsoft Most Valuable Professional for years 2016, 2015, 2014 2013 and 2012 from Microsoft. He also is a Microsoft Certified Professional for Programming in HTML5 with JavaScript and CSS3 Specialist. Programming is his passion. He is core member of Microsoft User Group Hyderabad. In his overall experience of 7+ years, his expertise includes Azure, C#, Swift, ASP.NET MVC, HTML 5, TypeScript, Object Oriented JavaScript, JavaScript Frameworks (Angular, Angular 2, Backbone, React), iOS. He also experiments on next generation JavaScript and Web technologies. Shravan's Blog: http://theshravan.net/blog Follow Shravan @ Twitter: @techieshravan