Jquery 从ASP.NET MVC2应用程序执行Ajax调用时出现问题
我正在将一个现有的ASP.NET应用程序转换为MVC2,我有一个使用Ajax通过jQuery调用的现有方法,以前可以使用,但现在不可用。因此,由于使用MVC2,我似乎需要做一些我无法理解的更改 我已经降低了代码的复杂性,但它仍然不起作用。这是我当前的代码: 点击按钮时触发的jQuery脚本Jquery 从ASP.NET MVC2应用程序执行Ajax调用时出现问题,jquery,ajax,asp.net-mvc-2,Jquery,Ajax,Asp.net Mvc 2,我正在将一个现有的ASP.NET应用程序转换为MVC2,我有一个使用Ajax通过jQuery调用的现有方法,以前可以使用,但现在不可用。因此,由于使用MVC2,我似乎需要做一些我无法理解的更改 我已经降低了代码的复杂性,但它仍然不起作用。这是我当前的代码: 点击按钮时触发的jQuery脚本 function leaveComment() { if (validate()) { $.ajax({ type: "POST", url: "/Pages/Post
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方法,但我在这里面临两个主要问题:
Test
发送对于那些经常使用这些东西的人来说(或者至少我希望是这样的:)这个错误可能很容易发现。以下是使这项工作正常进行所需的更改:
$.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" });
}
注意事项:
data
hash属性需要与我的示例相同,否则您将发送一个JSON编码的字符串,而ASP.NET MVC的默认模型绑定器不知道如何将其解析回操作参数。在ASP.NET MVC 3中,这一点已经改变,因为存在一个允许您发送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
}
});
值的方法,该属性在成功
回调中使用,来自服务器的响应如下所示:
{ 'Value': 'This is a test' }
...
url: '<%= Url.Action("PostBlogComment", "Pages") %>',
...
。。。
url:“”,
...
或者,如果这是一个外部javascript文件,您可以使用在视图中初始化的指向正确url的某个全局js变量,或者将此url作为DOM的一部分(例如作为锚href属性或HTML5data-*
属性),然后使用jQuery获取值工作得很有魅力!非常感谢,达林。编辑完后我不得不说哇!一个非常彻底和信息丰富的回答。但愿我能再给你几票;)