User970008
User970008

Reputation: 1155

Partial View SPA for Some Pages With a RenderBody for Others

I have a MVC 4 (Razor) app that is being converted to resemble more of a SPA single page app. It is not purely a SPA -- 5 of the pages use Ajax to load in the body section, while other one-off pages are not required to use Ajax.

I have everything working except for the home Index page. I need to link back to the index, but I'd like to keep using one layout master page. The problem is that I cannot figure out how to sometimes load the partial views and then other times render the page with the layout master.

I need to keep the @RenderBody for the non-Ajax pages.

<body>
   <section id="BodySection">
     @RenderBody 
   </section>
</body>

For the Ajax pages, on nav button click I Ajax the partial view into #BodySection using JQ.

function LoadPage(actionarg, controllerarg) {
        var link = '@(Url.Action("action", "controller"))';
        link = link.replace("action", actionarg);
        link = link.replace("controller", controllerarg);

        $.ajax({
            url: link,
            type: "POST",
            cache: false,
            async: true,
            data: { data: '' },
            success: function (result) {
                $("#BodySection").html(result);
            }
        });
    }

How can I mix the two types of page loading?

Upvotes: 0

Views: 2202

Answers (1)

tweray
tweray

Reputation: 1003

Not sure if it is the most practical way, but this is how I handle it:

First create 2 views, I will call them "page.cshtml" and "partialpage.cshtml", and 2 actions (or you can separate them into 2 controllers, depending on your request), let's call them "somecontroller/page" and "somecontroller/partialpage"

partialpage.cshtml:

@{
    Layout = "";
}
@*Exact page content here*@

page.cshtml

@{
    Layout = "Your master layout directory";
}
@Html.Action("somecontroller","partialpage")

When you need the page as partial view then use partialpage action, when you need the full page with master view then use page action.

This is just my own way, please let me know if anyone knows any practical way.

Thanks.

Upvotes: 1

Related Questions