How to call nested ajax call and send object data to controller in ASP.Net MVC 5

为君一笑 提交于 2019-12-24 08:02:04

问题


I have two controller

  1. Settings Controller

    Action - GetAvailableLocationsFor

  2. HomeController

    Action - Index

Steps I want to acheive

  1. Make ajax call to GetAvailableLocationsFor and then get the object data from success call back. No view is required for this Action.
  2. Now with the object data received make another ajax call to Index Action in HOMECONTROLLER and pass the object there.

Below is what I could achieve.

HomeController - GetAvailableLocationsFor

public ActionResult GetAvailableLocationsFor(int accountId, int groupId)
        {
            FullConfigMV configData = SetLoader.GetSettings(accountId, groupId);
           return // HOW TO RETURN configData from Here to first ajax call
}

HomeController - Index Action

[HttpPost]
public ActionResult Index(FullConfigMV data)
{
  //SECOND AJAX CALL SHOULD COME HERE
}

Nested Ajax call

<script>
    $(document).ready(function()
    {
        $("#tan").change(function()
        {
            alert(this.value);
            $.ajax({
                type: 'POST',
                url: '/Settings/GetAvailableLocationsFor',
                data: { accountId: 28462, groupId: 35},
                success: function (data) { // data should represent configObj

                    $.ajax({
                        type: 'POST',
                        url: '/Home/Index',
                        data: // WHAT TO WRITE HERE,
                        success: function (data) {
                            //WHATEVER
                        },
                        error: function () {
                            DisplayError('Failed to load the data.');
                        }
                    });

                },
                error: function () {
                    DisplayError('Failed to load the data.');
                }
            });


        });
    });
</script>

回答1:


A better approach would be to return a redirect in your GetAvailableLocationsFor action

return RedirectToAction("Index", "Home", configData)

Then in your ajax success instead of the second ajax call. Just handle whatever gets returned by Home/Index.




回答2:


Return JSON data from GetAvailableLocationsFor method. After in second ajax call you can send data like below:

data: JSON.parse(response),

this will get data in your parameter in Index method



来源:https://stackoverflow.com/questions/41706791/how-to-call-nested-ajax-call-and-send-object-data-to-controller-in-asp-net-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!