Invoking an MVC action with jQuery AJAX that does not return Json (instead of another view)

So I have MVC Action in my controller

public System.Web.Mvc.ActionResult Link(LinkType type) { switch (type) { case LinkType.IC: return RedirectToAction("Indication", "IndicationsController"); break; case LinkType.Pricing: break; case LinkType.Sheets: break; case LinkType.Analysis: break; case LinkType.Admin: break; default : break; } return View(@"~\Views\Indications\ShowAString.aspx", "", "Page is not available for selection."); } 

I want to call this action from jQuery, passing the integer value of the button that was clicked. So I have this in a button click method:

 $('#btnIc').live('click', function () { var typeJSON = {}; typeJSON["type"] = 1; $.ajax({ type: "POST", url: "<%= Url.Action("Link", "Home") %> ", dataType: "jsonData", data: typeJSON, success: function(data) { } }); }); 

Will it redirect the page or will it wait for me to do something with (data)?

Is this being done right?

+4
source share
3 answers

Returning the entire view in an AJAX request almost always fails. Instead, you want to return XML, JSON, or a piece of HTML. You can return the HTML fragment by returning partial by calling PartialView() in the controller.

If you are returning HTML, then your jQuery AJAX request should expect it, so change its data type to html . Then, in the jQuery callback, you can simply take the resulting HTML and add it to your page somewhere.

NOTE: you can use Request.IsAjaxRequest() to return AJAX data or a full view and use the same action for both kinds of requests. This helps with progressive improvement.

+4
source

Why not just do

 public ActionResult Link(LinkType type) { var obj = ...; //Object that you get from the LinkType. Whatever ShowAString returns. return Json(obj); } 
+2
source

You are not returning json, it looks like you are redirecting to another action that might return a view. You will need to set the action type in JsonResult and return your json object there.

+1
source

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


All Articles