dcolumbus
dcolumbus

Reputation: 9722

ASP.NET MVC 2: jQuery post string is null?

I'm not sure what's the issue, but I'm constructing a string and trying to pass it to my Controller Action. But when the action is executed, the data is null.

JavaScript:

var xml = "<Request><ZipCode>92612</ZipCode></Request>";

$.ajax({
    url: "/Home/GetXml",
    contentType: 'application/text; charset=utf-8',
    data: xml,
    success: function (result) { success(result); },
    type: "POST",
    datatype: "text"
});

Controller:

[HttpPost]
public ActionResult GetXml(string data)
{
    if (!String.IsNullOrEmpty(data))
    {    
        return View("Index", data);
    }

    return View("Index");
}

If I set a breakpoint on the if, the "data" is null. What gives?

Upvotes: 0

Views: 3391

Answers (2)

Lorenzo
Lorenzo

Reputation: 29427

try with

$.ajax({
    url: "/Home/GetXml",
    contentType: 'application/text; charset=utf-8',
    data: { data: xml },
    success: function (result) { success(result); },
    type: "POST",
    datatype: "text"
});

Upvotes: 1

dcolumbus
dcolumbus

Reputation: 9722

The answer: don't use contentType

Thanks to this question and answer: Asp.Net Mvc JQuery ajax input parameters are null

Upvotes: 2

Related Questions