Post HTML tag (codes) as string with ASP.net MVC & JQuery Post HTML tag (codes) as string with ASP.net MVC & JQuery jquery jquery

Post HTML tag (codes) as string with ASP.net MVC & JQuery


ASP.NET has built-in request validation that automatically helps protect against XSS and HTML injection attacks. If you want to explicitly disable this validation you could decorate the action you are posting to with the [ValidateInput(false)] attribute:

[HttpPost][ValidateInput(false)]   public ActionResult SaveArticle(ArticleModel model){    var JResult = new JsonResult();    if (ModelState.IsValid)    {        ...    }    return JResult;}

Also if you are running this on ASP.NET 4.0 for this attribute to take effect you need to add the following to your web.config:

<httpRuntime requestValidationMode="2.0" />

And if you are using ASP.NET MVC 3.0 you could decorate only the property on your model that requires HTML with the [AllowHtml] attribute:

public class ArticleModel {    [AllowHtml]    public string SomeProperty { get; set; }    public string SomeOtherProperty { get; set; }}

Also in your javascript function you probably want serialize() instead of serializeArray():

function JqueryFromPost(formId) {    var form = $(formId);    $.post(form.action, form.serialize(), function (data) {        //Getting the data Result here...    });}


You shouldn't use ValidateInput(false) as MSN said here: http://msdn.microsoft.com/en-us/magazine/hh708755.aspx Just use [AllowHtml] on your model property you want take html.

[AllowHtml]public String htmlContainer { get; set; }

Additionally I think that is better if you encode html and then post it to server.


Using [ValidateInput(false)] is a very bad practice which leads to many security breaches, [AllowHtml] on a model property is more secured and reliable way of doing this. But there is a much cleaner solution if you can't use a model property.

Simply Encode the text on Client Side(mycase javascript), Decode it on the serve side(Controller function).I used the below for my vb.net project.

var SearchStringValue = <p> some blah...blah data </p>

Now encoding the above variable.

var encodedSearchStringValue = window.escape(document.getElementById('SearchStringValue').value)

now pass encodeSearchStringValue to controller using ajax.

In the controller just decode the variable to get <p> some blah...blah data </p>.

Dim SearchStringValue = HttpUtility.UrlDecode(encodeSearchStringValue)

Hope this helps......... :)