【问题标题】:Problem performing Ajax call from ASP.NET MVC2 app从 ASP.NET MVC2 应用程序执行 Ajax 调用时出现问题
【发布时间】:2011-03-20 21:31:12
【问题描述】:

我正在将现有的 ASP.NET 应用程序转换为 MVC2,并且我有一个使用 Ajax 通过 jQuery 调用的现有方法,该方法以前有效,但现在无效。因此,由于使用了我无法弄清楚的 MVC2,我似乎需要做一些更改。

我已经降低了代码的复杂性,但它仍然不起作用。这是我当前的代码:

点击按钮触发的jQuery脚本

function leaveComment() {
if (validate()) {
    $.ajax({
        type: "POST",
        url: "/Pages/PostBlogComment",
        data: "{'name':'Test','url':'Test','email':'Test','body':'Test','postid':'Test'}",
        dataType: "json",
        success: function (msg) {
            //success code goes here
        },
        error: function (msg) {
           //error code goes here
        }
    });
}

};

在我的名为 Pages 的控制器中,我创建了以下方法:

public string PostBlogComment( string name, string url, string email, string body, string postid)
{
  return "This is a test";
}

调试时,我可以看到 PostBlogComment 方法被调用,但我在这里面临两个主要问题:

  1. 该方法的所有参数都作为空值接收,因此我没有可用的有用数据。对于现在的测试,所有参数都以Test 发送,您可以从代码中看到。
  2. 将结果返回给 Ajax 方法时,调用的是错误路径,而不是成功路径,即使该方法确实返回了正常的字符串(即使传入的参数为空)

对于那些经常使用这些东西的人来说,这个错误可能很容易发现(或者至少我希望如此:))

【问题讨论】:

    标签: jquery ajax asp.net-mvc-2


    【解决方案1】:

    以下是您需要进行的更改:

    $.ajax({
        type: 'POST',
        url: '/Pages/PostBlogComment',
        data: { 
            name: 'Test', 
            url: 'Test', 
            email: 'Test', 
            body: 'Test', 
            postid: 'Test'
        },
        success: function (result) {
            alert(result.Value);
        },
        error: function (msg) {
           //error code goes here
        }
    });
    

    和你的控制器动作

    public ActionResult PostBlogComment( 
        string name, 
        string url, 
        string email, 
        string body, 
        string postid
    )
    {
        return Json(new { Value = "This is a test" });
    }
    

    这可以通过引入视图模型来改进:

    public class PostViewModel
    {
        public string Name { get; set; }
        public string Url { get; set; }
        public string Email { get; set; }
        public string Body { get; set; }
        public string Postid { get; set; }
    }
    

    然后:

    public ActionResult PostBlogComment(PostViewModel model)
    {
        return Json(new { Value = "This is a test" });
    }
    

    注意事项:

    1. jquery AJAX 调用的 data 哈希属性需要作为我的示例,否则您将发送 JSON 编码的字符串,并且 ASP.NET MVC 的默认模型绑定器不知道如何解析为操作参数.在 ASP.NET MVC 3 中,这已经改变,因为有一个 JsonValueProviderFactory 允许您发送 JSON 请求。因此,如果您使用的是 ASP.NET MVC 3,您可以像这样发送您的 AJAX 请求,并且操作参数将被正确绑定:

      $.ajax({
          type: 'POST',
          url: '/Pages/PostBlogComment',
          data: JSON.stringify({ 
              name: 'Test', 
              url: 'Test', 
              email: 'Test', 
              body: 'Test', 
              postid: 'Test'
          }),
          contentType: 'application/json',
          success: function (result) {
              alert(result.Value);
          },
          error: function (msg) {
             //error code goes here
          }
      });
      
    2. ASP.NET MVC 中的所有控制器操作都必须返回 ActionResults。因此,如果您想要 Json,请返回 JsonResult

    3. 该操作将匿名类型传递给包含Value 属性的Json 方法,该属性在success 回调中使用,来自服务器的响应如下所示:

      { 'Value': 'This is a test' }
      
    4. 永远不要在你的 javascript 文件中硬编码这样的 url,否则你的应用程序在部署时可能会中断。处理 url 时始终使用 Url 助手:

      ...
      url: '<%= Url.Action("PostBlogComment", "Pages") %>',
      ...
      

      或者如果这是一个外部 javascript 文件,您可以使用在您的视图中初始化的一些全局 js 变量指向正确的 url,或者将此 url 作为 DOM 的一部分(例如作为锚点 href 属性或 HTML5 @987654334 @attribute),然后使用 jQuery 来获取值。

    【讨论】:

    • 工作就像一个魅力!非常感谢达林。
    • 编辑后我只想说哇!一个非常彻底和翔实的答案。希望我能给你几个额外的支持;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多