Friday, 15 July 2016

Html submission by ValidateInput and AllowHtml attribute in MVC4

Sometimes, your required to save Html data in the database. By default Asp.Net MVC doesn't allow a user to submit html for avoiding Cross Site Scripting attack to your application. Suppose you have below form and you can submit the Html in description textarea.

If you do this and try to submit it you will get the error as shown in fig.

However, if you want to do this, you can achieve it by using ValidateInput attribute and AllowHtml attribute.

ValidateInput Attribute

This is the simple way to allow the submission of HTML. This attribute can enable or disable input validation at the controller level or at any action method.

ValidateInput at Controller Level

  1. [ValidateInput(false)]
  2. public class HomeController : Controller
  3. {
  4. public ActionResult AddArticle()
  5. {
  6. return View();
  7. }
  8. [HttpPost]
  9. public ActionResult AddArticle(BlogModel blog)
  10. {
  11. if (ModelState.IsValid)
  12. {
  13. }
  14. return View();
  15. }
  16. }
Now, the user can submit Html for this Controller successfully.

ValidateInput at Action Method Level

  1. public class HomeController : Controller
  2. {
  3. public ActionResult AddArticle()
  4. {
  5. return View();
  6. }
  7. [ValidateInput(false)]
  8. [HttpPost]
  9. public ActionResult AddArticle(BlogModel blog)
  10. {
  11. if (ModelState.IsValid)
  12. {
  13. }
  14. return View();
  15. }
  16. }
Now, the user can submit Html for this action method successfully.

Limitation of ValidateInput attribute

This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should use AllowHtml attribute.

AllowHtml Attribute

This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.
  1. using System.ComponentModel.DataAnnotations;
  2. using System.Web.Mvc;
  3. public class BlogModel
  4. {
  5. [Required]
  6. [Display(Name = "Title")]
  7. public string Title { get; set; }
  8. [AllowHtml]
  9. [Required]
  10. [Display(Name = "Description")]
  11. public string Description{ get; set; }
  12. }
Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.

No comments:

Post a Comment