DaveDev
DaveDev

Reputation: 42175

How can I test if the current request is an ajax request in a Controller?

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?

Upvotes: 2

Views: 11995

Answers (3)

MrBliz
MrBliz

Reputation: 5898

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");
}

Upvotes: 2

jim tollan
jim tollan

Reputation: 22485

i generally use the old:

if (Request.IsAjaxRequest())

inside the controller.

Upvotes: 28

Stefanvds
Stefanvds

Reputation: 5916

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

Upvotes: 2

Related Questions