How to Call Controller Actions using JQuery in ASP.NET MVC

后端 未结 5 2072
粉色の甜心
粉色の甜心 2020-11-29 05:28

I\'ve been reading on this for a while and found that you can call a controller action by using:

$.ajax(\"MyController/MyAction\", function(data) {
    alert         


        
5条回答
  •  情歌与酒
    2020-11-29 05:55

    the previous response is ASP.NET only

    you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

    and then a similar block of code but simpler...

    $.ajax({ url: '/Controller/Action/Id',
             success: function(data) { alert(data); }, 
             statusCode : {
                 404: function(content) { alert('cannot find resource'); },
                 500: function(content) { alert('internal server error'); }
             }, 
             error: function(req, status, errorObj) {
                   // handle status === "timeout"
                   // handle other errors
             }
    });
    

    I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

    ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

提交回复
热议问题