Search code examples
asp.net-mvcasp.net-mvc-4razorrazor-2

How can I get rendered View for any Action inside different Contoller or Action?


I have some action's views that are dependant on settings from DB (for example display textbox or not). Settings are changed in admin controller. What I'd like to achieve is to have the preview of the changed views in admin's sidebox (right side of the screen) after the changes will be saved to DB.

Is there a way to get View result of another action (casually returns View()) with button (Save and Preview) click in form of string (HTML) to display in the sidebox?

Or maybe has anyone other and better idea?


Solution

  • Yes. They're called child actions. Simply, you just call the action you want rendered via Html.Action:

    @Html.Action("SomeAction", "SomeController")
    

    However, there's a couple of things to keep in mind. First, your child action should return PartialView. Otherwise, you'll get the full layout rendered again where you call the action. If you want to use the same action for both a regular view and as a child action. You can branch your return:

    if (ControllerContext.IsChildAction)
    {
        return PartialView();
    }
    
    return View();
    

    Second, if you only return PartialView, then the action should not be available to directly route to. Otherwise, someone could enter a URL in their browser to go to this child action and only the partial view would be returned, devoid of layout. You can prevent this from occurring using the ChildActionOnly attribute:

    [ChildActionOnly]
    public ActionResult MyAwesomeChildAction()
    {
        ...
    }
    

    Then, this action will only be available to be called via Html.Action.