Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if my action is being called by RenderAction?

I have an action that could potentially be called via a normal link, in which case I'd return a View(), or it could also be called via AJAX or RenderAction (ie as a Child Action) in which case I'd return a PartialView().

Sorting out the AJAX part is easy - but how can I test if my action is being rendered as a Child Action?

Ideally, I'd like to be able to write code like this:

if (Request.IsAjaxRequest() || Request.IsChildAction())
    return PartialView();

return View();

Obviously the Request.IsChildAction() does not exist - is there something simlilar, or do I just need to create a special ChildAction that always returns a PartialView?

like image 369
StanK Avatar asked Sep 14 '11 21:09

StanK


People also ask

Which of the following differentiates action from RenderAction?

The difference between the two is that Html. RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html. Action returns a string with the result.

What is action Render?

A render action is a public method on the controller class. You can define a render action method to return any data, but you can only safely use it if it returns an HTML markup string.

What is RenderAction in MVC?

RenderAction(HtmlHelper, String) Invokes the specified child action method and renders the result inline in the parent view. RenderAction(HtmlHelper, String, Object) Invokes the specified child action method using the specified parameters and renders the result inline in the parent view.


1 Answers

You were almost there:

public ActionResult Foo()
{
    if (Request.IsAjaxRequest() || ControllerContext.IsChildAction)
    {
        return PartialView();
    }
    return View();
}
like image 85
Darin Dimitrov Avatar answered Oct 22 '22 01:10

Darin Dimitrov