Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use allowhtml attribute for an action in mvc5

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

like image 833
javad Avatar asked Jun 17 '16 16:06

javad


People also ask

What does AllowHtml do?

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.

What is the importance of ValidateInput and AllowHtml in MVC?

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.


2 Answers

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>
}
like image 127
Shyju Avatar answered Nov 14 '22 20:11

Shyju


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)
{
 //
}
like image 24
Kld Avatar answered Nov 14 '22 22:11

Kld