0

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?

2 Answers 2

2

The answer: don't use contentType

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

Sign up to request clarification or add additional context in comments.

5 Comments

I was just about to post that solution after having fiddled with the code in Visual Studio. I'm glad you got it. You'll probably also notice that you're going to need to disable request validation for the GetXml action. ASP.NET will flip a hoo-hah if you try send it a request containing raw XML.
Disable request validation? What I'm noticing is that my ajax request is giving me a success, but none of my breakpoints within the controller action are being executed. Tells me that I'm not actually getting to the action...
If you dont disable request validation I suspect that the request is handled at an higher level and rejected from the MVC framework with maybe an HTTP 500 error
@Nathan, there's obviously a problem with sending raw XML to the controller. What would be my alternative?
As I said, disable request validation. Above the GetXml action definition add [ValidateInput(false)].
1

try with

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

10 Comments

He's passing a text dataType, not JSON. This will change the parameters of the request.
No matter what I do, the data is always null. I've tried using both post and ajax. No difference.
@dcolumbus: I have edited my answer. I wrote so fast and forgot to add the variable name. The default ModelBinder will do the job
@Lorenzo, any idea why I might be getting a success but my controller action isn't actually being executed?
@dcolumbus: you mean that the request will succeed but you are not able to debug in the code? You can try using Fiddler and see what's going on with the request/response
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.