获取JSonResult从ASP的Ajax.ActionLink [英] Getting JSonResult from ASP's Ajax.ActionLink

查看:151
本文介绍了获取JSonResult从ASP的Ajax.ActionLink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何真正得到使用Ajax.ActionLink控制器方法JSON?我试图寻找的网站,但我得到的最接近的事情是<一个href=\"http://stackoverflow.com/questions/227624/asp-net-mvc-controller-actions-that-return-json-or-partial-html\">ASP.NET返回JSON的MVC控制器动作或部分HTML

How do I actually get the JSON from a controller method using Ajax.ActionLink? I tried searching the website, but the closest thing I got was ASP.NET MVC controller actions that return JSON or partial html

和最佳答案实际上并没有告诉你如何从ajax.actionlink的SomeActionMethod得到JSON。

And the "best answer" doesn't actually tell you how to get JSON from the SomeActionMethod in the ajax.actionlink.

推荐答案

我个人不喜欢阿贾克斯。* 助手。在ASP.NET MVC&LT; 3它们污染我的HTML与JavaScript和ASP.NET MVC 3它们污染我的HTML与HTML 5 数据 - * 属性这是完全多余的(如锚的网址)。此外,他们不会自动解析JSON对象成功的回调也就是你的问题是什么。

Personally I don't like the Ajax.* helpers. In ASP.NET MVC < 3 they pollute my HTML with javascript and in ASP.NET MVC 3 they pollute my HTML with HTML 5 data-* attributes which are totally redundant (such as the url of an anchor). Also they don't automatically parse the JSON objects in the success callbacks which is what your question is about.

我正常使用 HTML * 帮手,这样的:

I use normal Html.* helpers, like this:

@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>

和我悄悄地AJAXify在单独的JavaScript文件:

and which I unobtrusively AJAXify in separate javascript files:

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

假设下面的控制器动作:

Assuming the following controller action:

[HttpPost]
public ActionResult SomeAction()
{
    return Json(new { someProperty = "Hello World" });
}


更新:

按照要求在评论部分下面是如何使用 Ajax来做到这一点。* 佣工(我再次重申,这只是如何能够实现插图和绝对不是我推荐,看得我最初的回答为我推荐的解决方案):

As requested in the comments section here's how to do it using the Ajax.* helpers (I repeat once again, that's just an illustration of how this could be achieved and absolutely not something I recommend, see my initial answer for my recommended solution):

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

和成功的回调里面:

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

这篇关于获取JSonResult从ASP的Ajax.ActionLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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