I am developing an MVC 5 project and I want to use CKEditor for input data. This data is saved as HTML, but when I try to display it, I get an error. See code
AllowHtml attribute is used to allow sending HTML content or codes to server which by default is disabled by ASP.Net MVC to avoid XSS (Cross Site Scripting) attacks. In XSS (Cross Site Scripting) attacks, a hacker tries to inject HTML or JavaScript code to a website via INPUT fields such as TextBoxes, TextAreas, etc.
The ValidateInput attribute is used to allow sending the HTML content or codes to the server which, by default, is disabled by ASP.NET MVC to avoid XSS (Cross-Site Scripting) attacks. This attribute is used to enable or disable the request validation. By default, request validation is enabled in ASP.NET MVC.
You can apply AllowHtml
attribute to the property which holds the markup in your view model class.
public class CreatePost
{
public string PostTitle {set;get;}
[AllowHtml]
public string PostContent { set;get;}
}
And use this view model in your HttpPost action method and everything will work fine.
[HttpPost]
public ActionResult Create(CreatePost viewModel)
{
// Check viewModel.PostContent property
// to do : Return something
}
Now just make sure you are using this property to build the text area to be used with CKEditor
@model CreatePost
@using (Html.BeginForm())
{
@Html.TextBoxFor(s => s.PostTitle)
@Html.TextAreaFor(s=>s.PostContent)
<input type="submit" />
}
@section Scripts
{
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace('Message');
</script>
}
Add the [ValidateInput(false)]
attribute the action (post) in the controller that you want to allow HTML for:
[ValidateInput(false)]
[HttpPost]
public ActionResult PostForm(Model model)
{
//
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With