15

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);
        }
    });
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
Mason240
  • 2,924
  • 3
  • 30
  • 46

1 Answers1

28

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);
    }
});
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • In your example, how does `test()` method get the `dealerId` from the JSON you are sending it? Should I assume it is passed as a parameter to the method, and you have simply omitted it? – crush Sep 16 '13 at 21:19
  • 3
    @crush yes, exactly. The MVC routing system is flexible enough to pull controller parameters from wherever they are available -- query string, post data, or route data. – McGarnagle Sep 16 '13 at 21:47
  • @McGarnagle: How can you add C# code into a external js file? I know how I can do in a html file, but not for a js file. – H. Pauwelyn Oct 20 '15 at 11:37
  • You could do it (include it in the routing system), but doesn't seem advisable. Better to factor the external dependencies out of the JS; or include the C# dependent JS as inline script, or as a partial view. – McGarnagle Oct 20 '15 at 18:08