In some cases I'm sending jQuery.get() requests to an Action Method, and in other cases it's a browser request. Is there any way for me to differentiate between them so I can return different action results accordingly?
Asked
Active
Viewed 1.1k times
3 Answers
27
i generally use the old:
if (Request.IsAjaxRequest())
inside the controller.

jim tollan
- 22,305
- 4
- 49
- 63
-
Can someone explain to me how this magic works? Edit: Found it. https://stackoverflow.com/questions/4885893/how-to-differentiate-ajax-requests-from-normal-http-requests – Pangamma Aug 17 '17 at 23:33
2
If you do want to return different action results, so use different actions. However if it MUST be the same, you could alter the url and send an extra parameter with it like
htt://mysite.com/controller/action?ajax=ajax
Besides that I wouldnt recommend to use Get's for AJAX. It's better practice to use post $.post
regarding security.
I very much advise every MVC developer to watch the HaaHa show: http://live.visitmix.com/MIX10/Sessions/FT05

Stefanvds
- 5,868
- 5
- 48
- 72
-
My requests are idempotent so I don't want to do POSTs. http://en.wikipedia.org/wiki/Idempotent – DaveDev Sep 01 '10 at 17:46
2
If they are different actions that you want to return then you could have a generic action that redirects to another action depending on the request
public ActionResult GetData()
{
if(Request.IsAjaxRequest())
return RedirectToAction("AjaxRequest");
else
return RedirectToAction("NonAjaxRequest");
}

MrBliz
- 5,830
- 15
- 57
- 81
-
late on +1-ing you here, but your answer is actually probably a better, more informative one than mine (from all those years ago :)). so, hopefully, DaveDev will pop in and change his decision at some point!! (btw - the pattern you use there is how is used to do things too in the 'old' days too), so definitely a good option based on mvc2/3. take care - jim – jim tollan May 10 '13 at 20:30