从 ASP.NET MVC2 应用程序执行 Ajax 调用时出现问题

发布于 2024-10-25 07:53:41 字数 1123 浏览 0 评论 0原文

我正在将现有的 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 方法时,将调用错误路径,而不是成功路径,即使该方法确实正常返回字符串(即使发送的参数为空),

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

I'm converting an existing ASP.NET app to MVC2, and I have an existing method that is called through jQuery using Ajax, that worked before, but does not work now. So it seems there are some change I need to do due to using MVC2 that I can't figure out.

I have reduced the complexity of the code, but it still do not work. This is my current code:

jQuery script that trigger on button click

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

};

Inside my controller called Pages, I have created the following method:

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

When debugging I can see that the PostBlogComment method gets called, but there are two major problems I'm facing here:

  1. All arguments to the method is received as null, so I have no useful data to work with. For testing now, all arguments are sent as Test as you can see from the code.
  2. When returning the result to the Ajax method, the error path is called, and not the success path, even it the method did return the string as normal (even if the parameters sent in was blank)

The error is probably easy to spot for those who work with these things regularly (or at least I hope so :))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

多情出卖 2024-11-01 07:53:42

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

$.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({
    类型:'发布',
    url: '/Pages/PostBlogComment',
    数据:JSON.stringify({
    名称:'测试',
    url: '测试',
    电子邮件:'测试',
    正文:“测试”,
    postid: '测试'
    }),
    内容类型:'应用程序/json',
    成功:函数(结果){
    警报(结果。值);
    },
    错误:函数(消息){
    //错误代码放在这里
    }
    });

  2. ASP.NET MVC 中的所有控制器操作都必须返回 ActionResults。因此,如果您想要 Json,则返回 JsonResult

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

    { 'Value': '这是一个测试' }
    

  4. 切勿在 javascript 文件中硬编码这样的 url,否则您的应用程序可能会部署时会中断。处理 url 时始终使用 Url 助手:

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

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

Here are the changes you need to make this work:

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

and your controller action

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

Which could be improved by introducing a view model:

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

and then:

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

Things to note:

  1. the data hash property of a jquery AJAX call needs to be as my example or you would be sending a JSON encoded string and the default model binder of ASP.NET MVC doesn't know how to parse back as action arguments. In ASP.NET MVC 3 this has changed as there is a JsonValueProviderFactory allowing you to send JSON requests. So if you were using ASP.NET MVC 3 you could send your AJAX request like this and the action parameters will be correctly bound:

    $.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. All controller actions in ASP.NET MVC must return ActionResults. So if you want Json then return a JsonResult.

  3. The action passes an anonymous type to the Json method containing a Value property which is used in the success callback and the response from the server would look like this:

    { 'Value': 'This is a test' }
    
  4. Never hardcode urls like this in your javascript files or your application might break when you deploy it. Always use Url helpers when dealing with urls:

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

    or if this was an external javascript file you could either use some global js variable that was initialized in your view pointing to the correct url or make this url as part of your DOM (for example as anchor href property or HTML5 data-* attributes) and then use jQuery to fetch the value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文