C# Tip Article
How to allow HTML string in MVC
Question
In MVC, how to allow HTML string in POST action?
Tip
HTML string is considered as dangerous input due to XSS attack, so MVC throws an error when it finds HTML string in POST payload.
In order to allow HTML input,
(1) Add [ValidateInput(false)] attribute in POST action. This allows HTML input in action level, that is, input will be not validated for all fields. For example,
[HttpPost] [ValidateInput(false)] [ValidateAntiForgeryToken] public ActionResult Create(Article article) { }
(2) Or add [AllowHtml] attribute to a specific property of data class. This is more granular approach, which now allows HTML for a Content field only.
public class Article { public int Id { get; set; } public string Title { get; set; } [AllowHtml] public string Content { get; set; } }
Answer
Add either [ValidateInput(false)] attribute in a controller action level or add [AllowHtml] attribute to a specific property in data class. [AllowHtml] is preferred.