我个人不喜欢Ajax.*
帮手。在 ASP.NET MVC data-*完全多余的属性(例如锚点的 url)。此外,它们不会自动解析成功回调中的 JSON 对象,这就是您的问题所在。
我用的是普通的Html.*
帮助者,像这样:
@Html.ActionLink(
"click me", // linkText
"SomeAction", // action
"SomeController", // controller
null, // routeValues
new { id = "mylink" } // htmlAttributes
)
这显然会产生normal HTML:
<a href="/SomeController/SomeAction" id="mylink">click me</a>
我在单独的 javascript 文件中不引人注目地进行 AJAXify:
$(function() {
$('#mylink').click(function() {
$.post(this.href, function(json) {
// TODO: Do something with the JSON object
// returned the your controller action
alert(json.someProperty);
});
return false;
});
});
假设控制器执行以下操作:
[HttpPost]
public ActionResult SomeAction()
{
return Json(new { someProperty = "Hello World" });
}
UPDATE:
根据评论部分的要求,这里是如何使用Ajax.*
助手(我再次重复一遍,这只是如何实现这一点的说明,绝对不是我推荐的东西,请参阅我推荐的解决方案的最初答案):
@Ajax.ActionLink(
"click me",
"SomeAction",
"SomeController",
new AjaxOptions {
HttpMethod = "POST",
OnSuccess = "success"
}
)
并在成功回调中:
function success(data) {
var json = $.parseJSON(data.responseText);
alert(json.someProperty);
}