6

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.

Community
  • 1
  • 1
user558594
  • 435
  • 2
  • 9
  • 14

1 Answers1

13

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);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Is there a way to do it with an Ajax.* helper, though? Is there any real downside to having those data- attributes (because I am using MVC 3)? – user558594 Jul 07 '11 at 20:43
  • @user558594, yes, there is a way. You specify a `OnSuccess` callback in the `AjaxOptions`. In this callback you could parse the JSON: `function success(data) { var json = $.parseJSON(data.responseText); }`. See my updated answer. – Darin Dimitrov Jul 07 '11 at 20:48
  • Right, but what exactly is the downside if you do this in MVC 3? Redundant data- attributes wouldn't add significantly to the file size that the user would download into the browser. – user558594 Jul 07 '11 at 20:59
  • @user558594, it's this redundancy that bothers me. When you do it once or twice it's fine, but when it becomes a habit and you do it on all your anchors and forms things get ugly. In addition to this did you see how you should manually parse the JSON in the success callback using `$.parseJSON`? That just totally sucks. Not to mention that you have far less control over the actual AJAX request compared to if you used standard jQuery methods. – Darin Dimitrov Jul 07 '11 at 21:00
  • I just tried your example (after modifying the controller and action to the ones I've already created). In my minified jQuery file, it says that the callback context is undefined. But it's infuriating because I can see the JSON being returned back. When you click on the link, it'll actually prompt you to download the JSON into a flat file. – user558594 Jul 07 '11 at 21:16
  • @user558594, did you include `jquery.unobtrusive-ajax.js` script to your page? You will need it if you intend to use any of the `Ajax.*` helpers. – Darin Dimitrov Jul 07 '11 at 21:23
  • I did. Plus it is going to the onsuccess method so the Ajax call is definitely working. Actually, I was referring to the way you suggested, using a regular HTML action link. – user558594 Jul 07 '11 at 21:34
  • @user558594, are you returning false from the `.click` handler? – Darin Dimitrov Jul 07 '11 at 21:43
  • Actually, I should really try and figure this out on my own. You already gave me what I needed to get a 200 response for the Ajax call and the data is being sent back. Thanks for all your advice. – user558594 Jul 07 '11 at 21:47
  • @DarinDimitrov, I'm trying to access the generated anchor. I tried to pass `this` but I receive a simple `Object` instance. – Shimmy Weitzhandler May 09 '13 at 01:42
  • @DarinDimitrov Inside the success callback, the data object is undefined for me? – JsonStatham Mar 27 '18 at 08:41