Bob
Bob

Reputation: 63

Ajax Post Parameter is Always Null in MVC app

I have a simple post that works in a test app

Controller Code

public ActionResult Delete(string Id)
{
    ... delete record ...
}

JavaScript

function delAnnouncement(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("Delete", "Announcements")",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "Id": "03d23684-098a-4ae8-8fa2-7d9ce70d63ef" }), // Hard coded for testing
        success: function (data) {
            $("#AnnouncementsPH").replaceWith(data);
        }
    });        
}

I have created a simple test application and it works there.

I am looking for any ideas as to what may exist in the existing application that would always cause the id passed to be null.

Things I have tried:
Route Info is the same between the two applications.
They are both secure https websites.
Other forms on the existing website work as expected. This is the only place a javascript post with a parameter is used. It is just the new view that lists any system announcements.
As far as I can tell the HTML is valid.
Fiddler show the data is being sent.
I have tried to simply hard code in the Id to pass.

I have no idea what could be causing the Post not to work.

Thanks for any suggestions

Edit 1: here is the fiddler Raw post

POST https://localhost:44300/Announcements/Delete HTTP/1.1
Host: localhost:44300
Connection: keep-alive
Content-Length: 39
Accept: */*
Origin: https://localhost:44300
X-Requested-With: XMLHttpRequest
Content-TypeOfNotification: application/json; charset=utf-8
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Referer: https://localhost:44300/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: jetbrains.charisma.main.security.PRINCIPAL=NmI4YmFhZTExMThjZDZkZjNmZTBhMDNiZWM4NmY3MDYzZWNiMWE3M2ZmZDM5ODMwYjViMjczN2ZkZmU3YmZlZTpyb290; TCSESSIONID=233EBE63123BA35468235F441F54D7E4; ASP.NET_SessionId=ycnx1ejeyahzipwduux2quqz; __RequestVerificationToken=FnOKGFfBZKEBX4E0KBoV9133e5KK3h9Pd_OjDzNPjv7ifMTMk5uHUPmT621hOQFyOCwW5IhdewKLPDMs2_9jY2vVwrHLYOU9f0F86mN-NoQ1; .AspNet.ApplicationCookie=V8ZnbAx_2_H1Wx946VLcQ235XplzC-uvKdw4CP7Sm8ZVnJu9pG63EuzC0ptOZZNBvzZkRjB0RJS25Pn1WHOzeQSrqoWl87keqRDS6_vMwZ9L6PgKU0rJz7OhD7eKps8l3tzR097zI5WbU_chUZFKLLw1c__rfN3Fy6BbHC1qNtgx0C86AShhG5EsNiruYqJZn-Uj7Z2h75YcZctCFniMyuzD-9RetcMjkN3_PbAJg-_urfntG9NwsMEQdBf1b3K9H3GP_wUYRhnbQdNZpuAkAEa6bVfJiHrnKFhnhLkP8BAfocbMKES1wQKbXBfcNn62cEKUu3On3lHNCNN4zEvOhxF1aDaBk-yghOtvtNkROeFTKMQFD0U-XXAf-RKm0Nwgp1Tb2Ip2U42vshDRNGXQSkOojisVUxiPmkrxDtckNycQd0br1cFSqxfeXyg3cg_vKUP1VMBQcBQxZO6MVLSCDdcpANyoE43IoLp3BHgURJZP88vF18JfVV646XGOZ3QU

Id=03d23684-098a-4ae8-8fa2-7d9ce70d63ef

As you can see the Id is posted to the controller, just not parsed and supplied to the parameter in the method.

Upvotes: 5

Views: 17091

Answers (5)

Andy Brown
Andy Brown

Reputation: 5522

I have wasted nearly a day on this, but finally got this working using JQuery and making sure I waited for response before continuing. Working client script:

 $.post('/ex/edited/', {
            ExId: @Model.ExId.ToString(),
            ExName: ExName
        })

            .done(function (response) {
                if (response.redirectUrl) {
                    window.location.href = response.redirectUrl;
                } else {
                    alert(response.errorMsg);
                }
            });

Upvotes: 0

Craig Everett Jones
Craig Everett Jones

Reputation: 81

I haven't found this answer anywhere else so I had to discover it through experimentation.

  1. You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).

  2. So client side, you have to set content type properly, and precede your data with "data=" + JSON.stringify(mydata), where "data" is the key name you are adding.

Like this:

$.ajax({
    type: "POST",
    url: URL,
    data: "data="+JSON.stringify(data),
    contentType: "application/x-www-form-urlencoded; charset=utf-8"

On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like this:

[HttpPost]
[Authorize]
public ActionResult Index (string data) // <-- key name
{
   MyObjectType MyFinalObject = JsonConvert.DeserializeObject<MyObjectType (data);
}

Upvotes: 7

ChickenFeet
ChickenFeet

Reputation: 2813

None of the answers worked for me, so instead I successfully solved with:

Javascript with JQuery:

function sendAjaxPostRequest(url, id, value) {
    $.post(url+'?id='+id+'&value='+value,
        function (returnedData) {
            console.log(returnedData);
        });
}

C# ASP.NET:

// POST api/<controller>
public void Post(int id, string value)
{
    Console.WriteLine($"{id}: {value}");
}

The Post parameter list signature must match the POST request url, e.g. ?id=123 means there must be a method Post(int id). Hope this helps someone.

Make sure to test your back-end with Postman before you blaim your front-end JS !


Strangely JS's $.ajax({ ... }); did not work by itself, but if I used both JQuery's $.post(...); and $.ajax({...}) POST requests, then both of them worked - very odd.

Upvotes: 1

Manmanwahaha Ma
Manmanwahaha Ma

Reputation: 126

You can append the parameter like:

var targeturl = '@Url.Action("Test", "Controller")?id=' + ID;

$.ajax({
    url: targeturl,
    type: "GET",
    success: function(data) { },
    error: function (data) { }
});

Or you may use the jQuery ajax data parameter directly:

$.ajax({
  type: "POST",
  url: '@Url.Action("Test", "Controller")',
  data: { id: "your-id" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

References: http://api.jquery.com/jquery.ajax/

Upvotes: 8

Ross Bush
Ross Bush

Reputation: 15175

I don't think you have to use JSON.stringify for the data. By default they will get values will be sent as Jason using ajax.

Try This

data : { Id: "03d23684-098a-4ae8-8fa2-7d9ce70d63ef" } 

Upvotes: 1

Related Questions