简体   繁体   中英

Calling a controller method via javascript

I have an ASP.NET application where I am invoking a controller methode from JavaScript. My JavaScript code looks like this:

function OnNodeClick(s, e) {
    $.ajax({
        type: "POST",
        url: '@Url.Action("DeviceManifests", "Home")',
        data: { selectedRepo: e.node.name },
        success: function (data) {
            if (data != null) {
                $('#GridView').html(data);
            }
        },                   
        error: function (e) {
            alert(e.responseText);
        }
    });
}

This calls the Home controller's DeviceManifests() method. This is what the method looks like:

 public ActionResult DeviceManifests(Guid selectedRepo)
 {
    var repoItem = mock.GetRepoItem(selectedRepo);

    return View("Delete", repoItem.childs);
 }

The method gets invoked but the problem is the Delete-View doesn't get rendered. There's no error, just nothing happens.

How can I update my code to get my desired behaviour?

Do like below code so if you have error you will have it in alert box or success result will rendered in DOM

 $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: '@Url.Action("DeviceManifests", "Home")',
            data: { selectedRepo: e.node.name },
            dataType: "html",
            success: function (data) {
                if (data != null) {
                      $('#someElement').html(data);
                    }

                }                  
            },
            error: function (e) {
                alert(e.responseText);
            }
        });

You can do the redirect in the javascript side.

function OnNodeClick(s, e) {
    $.ajax({
        type: "GET  ",
        url: '@Url.Action("DeviceManifests", "Home")',
        data: { selectedRepo: e.node.name },
        success: function (msg)
        {
            window.location = msg.newLoc;
        }
    });
}

Make sure you include the redirect url in action and return JsonResult and not ActionResult. I'd also include pass the guid so that the destination Action and let it look up the data.

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