how to use allowhtml attribute for an action in mvc5

15,400

Solution 1

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>
}

Solution 2

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)
{
 //
}

Solution 3

In order to use the [ValidateInput(false)] attribute, first you have to add the attribute requestValidationMode="2.0" in your httpRuntime tag in the site's Web.config:

<system.web>
    <httpRuntime targetFramework="4.5.1" requestValidationMode="2.0" />
    ...
</system.web>

That worked for me.

Share:
15,400
javad
Author by

javad

Updated on June 09, 2022

Comments

  • javad
    javad almost 2 years

    I am developing an mvc 5 project and I want to use ckEditor for input data so in this editor I saved data
    after I could insert data but when dispalying it has an error See Imaage