开发者

Getting JSonResult from ASP's Ajax.ActionLink

How do I actuall开发者_JAVA技巧y 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

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


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.

I use normal Html.* helpers, like this:

@Html.ActionLink(
    "click me",           // linkText
    "SomeAction",         // action
    "SomeController",     // controller
    null,                 // routeValues
    new { id = "mylink" } // htmlAttributes
)

which obviously generate normal HTML:

<a href="/SomeController/SomeAction" id="mylink">click me</a>

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" });
}

UPDATE:

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" 
    }
)

and inside the success callback:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜