Search code examples
.netasp.net-mvc-3modelviewmodelpartialviews

MVC3 .net Multiple Model or a Single View Model


I want to build a webpage which has 3 tabs (and thus 3 divs): Tab 1 - Update Personal Details Tab 2 - Check Order Tab 3 - Change logon details

There are 2 ways to implement this as far as I can tell, but would like to know best practice.

First would be to have 3 Partial Views that implement a separate Model each Second would be to have 3 Partial Views that implement a single ViewModel

The first option if using Partial Views will cause an error of "Expect Model A but got Model B" I believe you can use RenderAction to get around this, but is that best practice?

Opinions welcome.

Thanks


Solution

  • Looking at the names of the tabs, 'Update Personal Details', 'Check Order' and 'Change logon details' - it seems that these are fairly different, but related options that a user could do.

    To me, it would make sense to split these up into three different actions with three different views, meaning that you only render the action for the visible tab. This way, if the user only wanted to, say, update their details, the server isn't doing up the DB queries to check the order

    You would use some css to style it up so that it looks like three tabs, but each tab really would be a link which which did a new request, just making it look like there were three tabs.

    e.g.

    <div id="content">
        <ul>
           <li class="active">Update Personal Details</li>
           <li>@Html.ActionLink("Check Order","CheckOrder")</li>
           <li>@Html.ActionLink("Update Logon Details","UpdateLogonDetails")</li>
        </ul>
        <div id="tab1" />
         ... Update Personal Details Tab... etc
        </div>
        ... tab2 and tab 3 not included...
    </div>
    

    The actions for CheckOrder and UpdateLogonDetails would render essentially the same view, but a different tab would be showing.

    This would create the illusion that it was all run using tabs, even though it wasn't.

    Then, when you had that all running, you could update those links using JQuery to fire the requests via AJAX, returning the results as Partial Views and updating the content div with the result. This means that people with Javascript enabled get the proper 'ajax' experience, but that it still works OK for those with javascript disabled.