简体   繁体   中英

Making an AJAX request to an MVC controller and getting the data from the response in js

On button click I am trying to send a product name value that the user enters into a textbox to the server to be modified and then back to the page using AJAX. I am getting into the ChangeName method in the controller but not getting into my success function to alert the new name.

The JS:

    $("#changeNameButton").click(function () {
        var productName = $("#Name").val();

        $.ajax({
            url: '/Products/ChangeName/',
            type: 'POST',
            dataType: 'JSON',
            data: {name: productName},
            success: successFunc
        });
    });


    function successFunc(data) {
        alert(data);
    }

The controller:

    public string ChangeName(string name)
    {
        string changedName = ChangeNameHelper(name);
        return changedName;
    }

If anyone can give recommendations on the proper way to make asynchronous calls to a controller in MVC5/6 this would be great.

My main problem is that I am never getting into the successFunc() on response.

Regarding your comment, if you return just a string MVC will convert that to json.

Now, in your updated code you still call a method inside itself. Please call string changedName = ChangeNameForResult(name); or any function with another name.

Install Newtonsoft.Json via nuget package manager and in your controller do this

Public ActionResult ChangeName(string name)
{
     // get your object you want to serialize let's say res
     return JsonConvert.SerializeObject(res);

}

I needed to set dataType: 'text' rather than JSON since I am returning a simple string.

dataType is the type of data being returned and contentType is the type of data being sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM