问题从ASP.NET MVC2应用程序进行Ajax调用 [英] Problem performing Ajax call from ASP.NET MVC2 app

查看:111
本文介绍了问题从ASP.NET MVC2应用程序进行Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将现有的ASP.NET应用程序来MVC2,我有一个通过jQuery的使用Ajax,这工作之前调用,但现在不工作,现有的方法。因此,似乎有一些变化,我需要做的,由于使用MVC2,我想不通。

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.

我已经减少了的code的复杂性,但它仍然不工作。这是我目前的code:

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

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

};

在我的控制器称为网页,我创建了下面的方法:

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

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

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

  1. 要方法的所有参数被接收为空,所以我没有有用数据的工作。就目前的测试,所有参数都以测试,你可以从code见。
  2. 当返回结果给Ajax方法,错误路径被调用,而不是成功路径,甚至它的方法并返回字符串为正常(即使在发送的参数是空白的)
  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 :))

推荐答案

下面是改变你需要做这项工作:

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

和你的控制器动作

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

然后:

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

注意事项:

  1. 数据 jQuery的AJAX调用的散列属性需要像我的例子或者你会发送一个JSON恩codeD字符串和默认ASP.NET MVC的模型绑定不知道如何解析早在行动参数。在ASP.NET MVC 3这种情况已经改变,因为一个<一个href="http://davidhayden.com/blog/dave/archive/2011/01/07/JsonValueProviderFactoryASPNETMVC3.aspx">JsonValueProviderFactory让您发送的JSON请求。所以,如果你正在使用ASP.NET MVC 3,你可以把你的AJAX请求这样的操作参数将被正确绑定:

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

  • 在ASP.NET MVC所有的控制器动作必须返回ActionResults。所以,如果你想要的Json然后返回一个<一个href="http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult.aspx">JsonResult.

    动作传递一个匿名类型的的Json 方法包含属性,它是用在成功回调,并从服务器的响应是这样的:

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

  • 像这样在你的JavaScript文件或应用程序决不硬code网址可能会在部署时打破它。总是在使用URL处理使用URL助手:

  • 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") %>',
    ...
    

    如果这是一个外部JavaScript文件,你既可以使用已在视图中指向初始化到正确的URL一些全局JS变量或者使这个网址为您的DOM(例如作为锚的href属性或HTML5 <$的一部分C $ C>数据 - * 属性),然后使用jQuery来获取值

    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.

    这篇关于问题从ASP.NET MVC2应用程序进行Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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