Getting JSonResult from ASP Ajax.ActionLink

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

And the “best answer” doesn't really tell you how to get JSON from SomeActionMethod in ajax.actionlink.

+6
source share
1 answer

Personally, I don't like the Ajax.* . On ASP.NET MVC <3, they pollute my HTML with javascript, and on ASP.NET MVC 3 they pollute my HTML with HTML 5 data-* attributes that are completely redundant (e.g. binding url). In addition, they do not automatically parse JSON objects in the successful callbacks in question.

I use regular Html.* Helpers, for example:

 @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 stated in the comments section here, how to do this with the help of Ajax.* (I repeat again, this is just an illustration of how this could be achieved, and absolutely not what 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); } 
+13
source

Source: https://habr.com/ru/post/892268/


All Articles