在 MVC 4 中使用 $.ajax 发出 AJAX 请求 [英] Make an AJAX request using $.ajax in MVC 4

查看:27
本文介绍了在 MVC 4 中使用 $.ajax 发出 AJAX 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在带有 Razor 的 MVC 4 中使用 $.ajax 发出 AJAX 请求.我不确定如何实现它.

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

使用此视频我能够成功地进行链接驱动的调用返回的数据,但我似乎无法从 jquery 函数内部做同样的事情.我似乎找不到有关如何执行此操作的任何基本示例.这就是我正在使用的:

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);
        }
    });
}

推荐答案

您只需要将其设为 ActionResult.此外,如果您使用 Ajax POST,则需要使用 HttpPost 属性标记操作.试试这个:

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 的控制器/动作参数顺序错误——应该先是ActionName",然后是ControllerName"
  2. 对于Url.Action,如果控制器类是HomeController",那么你只需要Home"
  3. JQuery 选项语法错误 -- 应该是 success: function(data) {}.
  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);
    }
});

这篇关于在 MVC 4 中使用 $.ajax 发出 AJAX 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆