How can I test if the current request is an ajax request in a Controller?
Solution 1
i generally use the old:
if (Request.IsAjaxRequest())
inside the controller.
Solution 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
Solution 3
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");
}
DaveDev
Updated on July 14, 2022Comments
-
DaveDev almost 2 years
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?
-
DaveDev over 13 yearsMy requests are idempotent so I don't want to do POSTs. en.wikipedia.org/wiki/Idempotent
-
jim tollan almost 11 yearslate 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
-
Pangamma over 6 yearsCan someone explain to me how this magic works? Edit: Found it. stackoverflow.com/questions/4885893/…