Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX PUT Request to C# Controller [closed]

I am trying to update records in a database using AJAX requests. I'm able to insert using similar to the below, but am not successful when I attempt to update or delete.

Here is my ajax PUT method:

$('#updateCr').click(function(e) {
    e.preventDefault();
    var updatedData = {
        CrId: $('#CrId').val(),
        CrName: $('#CrName').val(),
        CrStatus: $('#CrStatus').val(),
        CrPriority: $('#CrPriority').val(),
        CrTitle: $('#CrTitle').val(),
        CrDescription: $('#CrDescription').val()
    };
    console.log(changeRequest);

    $.ajax({
        type: "PUT",
        url: "@Url.Action("MyControllerAction", "Home")",
        content: "application/json; charset=utf-8",
        dataType: "json",
        data: updatedData,
        cache: false,
        success: function(d) {
            if (d.success == true)
                window.location = "index.html";
            else {}
        },
        error: function(xhr, textStatus, errorThrown) {
            // TODO: Show error
        }
    });

And here is my Controller

[HttpPut]
public JsonResult MyControllerAction(UpdatedDataObject updatedData)
{
    try
    {
        myModel.UpdateDataMethod(updatedData);
    }
    catch (Exception e)
    {
        var theerrror = e.ToString();
        return Json(new { result = theerrror });
    }

    return Json(new { result = "Success" });
}

When submitting the data, the controller is triggered, but it is not receiving a JSON object. What am I doing wrong here?

like image 713
Michael Buchok Avatar asked Dec 22 '25 04:12

Michael Buchok


2 Answers

The issue is a typo. The returned JSON property is called result. In your JS code you use success. Also note that you're sending application/x-www-form-urlencoded data, not application/json. Thankfully this isn't an issue as the ModelBinder will work for both types of request. Try this:

$.ajax({
    type: "PUT",
    url: "@Url.Action("MyControllerAction", "Home")",
    dataType: "json",
    data: updatedData,
    cache: false,
    success: function(d) {
        if (d.result) {
            window.location.assign("index.html");
        } else { 
            console.log('do something constructive with the error here...');
        }
    },
    error: function(xhr, textStatus, errorThrown) {
        // TODO: Show error
    }
});

Finally, it seems a little redundant to redirect the user to another screen when the result of the AJAX request is successful. If that is the behaviour you require, then the point of AJAX is moot and you may as well use a standard form submission.

like image 103
Rory McCrossan Avatar answered Dec 23 '25 18:12

Rory McCrossan


I've found that including JSON.stringify() often solves these sorts of issues for me

data: JSON.stringify(updatedData),

total code would look like this:

$.ajax({
    type: "PUT",
    url: "@Url.Action("MyControllerAction", "Home")",
    content: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(updatedData),
    cache: false,
    success: function(d) {
    if (d.success == true)
    window.location = "index.html";
    else {}
         },
         error: function(xhr, textStatus, errorThrown) {
    // TODO: Show error
  }
});
like image 36
Nathan Koop Avatar answered Dec 23 '25 17:12

Nathan Koop