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

我正在将现有的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. 该方法的所有参数都被接收为null,因此我没有可用的有用数据。 现在进行Test ,从代码中可以看到所有参数都作为Test发送。
  2. 将结果返回到Ajax方法时,将调用错误路径,而不是成功路径,即使方法确实正常返回字符串(即使发送的参数为空)

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

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

 $.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. 该操作将匿名类型传递给Json方法,该方法包含在success回调中使用的Value属性,并且来自服务器的响应如下所示:

     { 'Value': 'This is a test' } 
  4. 切勿在javascript文件中对此类url进行硬编码,否则您的应用程序在部署时可能会中断。 在处理url时始终使用url助手:

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

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