Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

asp.net mvc - Make an AJAX request using $.ajax in MVC 4

I am trying to make an AJAX request using $.ajax in MVC 4 with Razor. I'm not sure how to implement it.

Using this video I was able to successfully make a link-driven call that returned data, but I can't seem to do the same thing from inside a jquery function. I can't seem to find any basic examples of how to do this. This is what I am working with:

HomeController.cs

        public string test(){
             return "It works";
        }

View.cshtml

function inventory(dealerID) {
    $.ajax({
        url: '@Url.Action("HomeController","test")',
        data: {dealerID: dealerID},
        type: 'POST',
        success: function(data) {
            process(data);
        }
    });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You just need to make it an ActionResult. Also, if you're using an Ajax POST, then the action needs to be marked with the HttpPost attribute. Try this:

[HttpPost]
public ActionResult test(string dealerID)
{
    return Content("It works");
}

Edit Actually, there are a few other problems with the syntax.

  1. Url.Action has the controller/action parameters in the wrong order -- should be "ActionName" first, then "ControllerName"
  2. For Url.Action, if the controller class is "HomeController", then you need just "Home"
  3. The JQuery options syntax is wrong -- should be success: function(data) {}.

$.ajax({
    url: '@Url.Action("test", "Home")',
    data: {dealerID: dealerID},
    type: 'POST',
    success: function(data) {
        alert(data);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...