Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a strongly typed master page using a base controller in ASP.NET MVC
    text
    copied!<p>Following the <a href="http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx" rel="noreferrer">NerdDinners</a> example, I am interested in creating a strongly typed Master Page. In order to achieve this, I use a base controller which retrieves the data for the master page. All other controllers inherit this class. Similarly, I have <code>ViewModels</code> for the master page and any other views. The view <code>ViewModel</code> classes inherit from the master page's <code>ViewModel</code>.</p> <h3>Question</h3> <p>How should a child controller ensure that the master page's data is passed to the View without setting the properties of its <code>ViewModel</code> that pertain to the master page itself?</p> <p>My the master page will display a number of buttons, which are determined in an XML file, hence the <code>Buttons</code> class that I am populating.</p> <p><strong>MasterPage ViewModel Code Snippet</strong></p> <pre><code>using System.Collections.Generic; namespace Site1.Models { public class MasterViewModel { public List&lt;Button&gt; Buttons{set; get;} } } </code></pre> <p><strong>View <code>ViewModel</code></strong> </p> <pre><code>namespace Site1.Models { public class View1ViewModel : MasterViewModel { public SomeDataClass SomeData { get; set; } } } </code></pre> <h3>Base Controller</h3> <pre><code>using System.Collections.Generic; using System.Web.Mvc; using Site1.Models; namespace Site1.Controllers { public abstract class BaseController : Controller { protected MasterViewModel model = new MasterViewModel(); public BaseController() { model.Buttons = new List&lt;Button&gt;(); //populate the button classes (doesn't matter how) PopulateButtons(model.Buttons); } } } </code></pre> <p><strong>View's controller:</strong> </p> <pre><code>using System.Web.Mvc; namespace Site1.Controllers { public class View1Controller : BaseController { public ActionResult Index() { Models.View1ViewModel viewModel = new Models.View1ViewModel(); SomeDataClass viewData = new SomeDataClass() //populate data class (doesn't matter how) PopulateDataClass(viewData); viewModel.SomeData = viewData; //I WANT TO ELIMINATE THE FOLLOWING LINE! viewModel.Buttons = model.Buttons; return View("Index", viewModel); } } } </code></pre> <p>The master page inherits <code>System.Web.Mvc.ViewMasterPage&lt;Site1.Models.MasterViewModel&gt;</code>.</p> <p>The view inherits <code>System.Web.Mvc.ViewMasterPage&lt;Site1.Models.View1ViewModel&gt;</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload