Getting JSonResult from ASP's Ajax.ActionLink

2019-03-10 08:26发布

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

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

1条回答
甜甜的少女心
2楼-- · 2019-03-10 09:22

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);
}
查看更多
登录 后发表回答