David Molyneux
David Molyneux

Reputation: 304

MVC Layout with Menu

I'm new to MVC and I'm trying to make use of the Layout Page So far I have the following layout page:

...

<div class="container-full body-content">

    <h2>@ViewBag.Title</h2>
    <div class="row">
        @if (Request.IsAuthenticated)
        {
            <div class="col-sm-3">
                @{Html.RenderAction("MenuPartial", "Layout");}
            </div>
            <div class="col-sm-9" style="background-color:aqua">
                @RenderBody()
            </div>
                    }
                    else
                    {
                        @RenderBody()
                    }
    </div>
...

Is there a way to get MVC to just re-render the render body rather than doing a full post back and re-loading the navigation menu each time a page changes?

Upvotes: 0

Views: 574

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239220

First, MVC doesn't do "postbacks". If you click a link, that's just a GET request. If you actually submit a form, it will send the request as a POST, but the destination could be an entirely different view or the same.

Second, taking an action like clicking a link or submitting a form within a web browser by default sends a request to the server and then entirely replaces the user's rendered view with a the response from the server. That necessitates the the server send back a full HTML document, including any associated layout.

If you want to replace just a portion of the HTML page without changing the user's view, that requires using AJAX. You send an AJAX request to request an action that will return a partial view. In other words, it will not utilize the layout you've defined for the web application. You, then, are responsible for replacing the appropriate portion of the DOM client-side with the server's response. There's a plethora of client-side JavaScript libraries that can help you manage this type of workflow, but they're all frameworks in their own right. In other words, they handle routing, models, views, etc. These are what's referred to as SPAs, or Single Page Applications. When you create a SPA, the server is relegated to a pure support role, only providing endpoints allowing you to retrieve or update data. Web Api is a popular choice here exactly for that reason; as all the MVC machinery is unnecessary.

If you're just looking to optimize things by say not having to render the child action that returns the menu, you can employ OutputCache on the child action so that for a period of time, the action will not need to run again, and the HTML output it generated can just be dumped directly into the appropriate place in the layout.

Upvotes: 2

Related Questions