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 开发者_如何学Cresults accordingly?
i generally use the old:
if (Request.IsAjaxRequest())
inside the controller.
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
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");
}
精彩评论