asp.net-mvc-3 – 从ASP的Ajax.ActionLink获取JSonResult

如何使用Ajax.ActionLink从控制器方法实际获取 JSON?我试着搜索网站,但最接近的是 ASP.NET MVC controller actions that return JSON or partial html

并且“最佳答案”实际上并没有告诉您如何从ajax.actionlink中的SomeActionMethod获取JSON.

解决方法

我个人不喜欢Ajax.*助手.在ASP.NET MVC中< 3他们用javascript污染我的HTML,在ASP.NET MVC 3中,他们使用完全冗余的HTML 5 data- *属性污染我的HTML(例如锚点的url).此外,它们不会自动解析成功回调中的JSON对象,这就是您的问题所在. 我使用普通的Html.*助手,像这样:
@Html.ActionLink(
    "click me",// linkText
    "SomeAction",// action
    "SomeController",// controller
    null,// routeValues
    new { id = "mylink" } // htmlAttributes
)

这显然会产生正常的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" });
}

更新:

根据评论部分的要求,这里是如何使用Ajax.*助手(我再次重复一遍,这只是说明如何实现这一点,绝对不是我推荐的东西,请参阅我推荐的解决方案的初步答案):

@Ajax.ActionLink(
    "click me","SomeAction","SomeController",new AjaxOptions { 
        HttpMethod = "POST",OnSuccess = "success" 
    }
)

并在成功回调中:

function success(data) {
    var json = $.parseJSON(data.responseText);
    alert(json.someProperty);
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...