0

I need to pass html as parameter using json asp.net mvc2

I am trying to do like this:

      $.ajax({
            type: "POST",
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            url: "/DefaultView/GeneratePDF",
            data: { "pdf": JSON.parse($("#displayContainer").html()) },
            success: function (data) {
                //nothing here
            }
        });

but it throws the "Uncaught SyntaxError: Unexpected token < " error.

using stringify() I am getting null here:

[HttpPost]
    [ValidateInput(false)] 
    public virtual ActionResult GeneratePDF(string pdf)
    {
        pdf <---

Does anyone have any idea what should I to do?

Thanks in advance.

Hugo S. Mendes
  • 1,076
  • 11
  • 23

2 Answers2

1

Use the stringify method of JSON:

 $.ajax({
         type: "POST",
         dataType: "json",
         contentType: 'application/json; charset=utf-8',
         url: "/DefaultView/GeneratePDF",
         data: { "pdf": JSON.stringify($("#displayContainer").html()) }, //change to stringify
         success: function (data) {
         //nothing here
        }
      });

EDIT: If you are using MVC 2 Model Binding to JSON is not supported. See this post - Always getting null values in controller for ajax post

Community
  • 1
  • 1
Jason Roell
  • 6,679
  • 4
  • 21
  • 28
0

I solved my problem with the help of this link:

link

... I needed to reference Microsoft.Web.Mvc and to add a call in my application_start (global.asax) like this:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

I also needed to make use of json2js

As @Jason Roell said, We can't use stringify with MVC 2.. the model binder doesn't knows how to parse the value correctly.

After all, everything works as expected.

Thanks.

I hope it helps someone.

Hugo S. Mendes
  • 1,076
  • 11
  • 23