tags:

views:

48

answers:

2
  • I want to insert a user control on to a master page
  • The user control is a basic menu that lists categories of items
  • I want to pull the category list dynamically from SQL Server
  • I can do this in web forms using code behind, but how do you go about this in MVC? Thank you

Categories.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
<ul> 
<% foreach (string category in Model.Categories ) { %> 
  <li> 
     <%= Html.Encode(category) %> 
  </li> 
<% } %> 
</ul>
A: 

this is in your Controller:

ViewData["CategoryList"] = _categoryService.GetCategoryList();

this exists in a file called NameOfMyPartial.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<% foreach (var category in (IList<Category>)ViewData["CategoryList"])) { %>
    // do stuff with category
<% } %>

Then in your Master page:

<% RenderPartial("NameOfMyPartial"); %>
DaveDev
This works, but I would not advise to use the ViewData collection. It's too easy to mistype magic strings like these and there will be no compile-time error when you do mistype them. Custom Viewmodels are usually the better choice (see http://devermind.com/linq/aspnet-mvc-using-custom-viewmodels-with-post-action-methods/ )
Adrian Grigore
@Adrian, I agree. I actually made a big stink in the office about using ViewData recently. Everything should be in a View Model. But for the sake of this example, I wanted to keep it as simple as possible.
DaveDev
Thank you both.
Muad'Dib
MvcContrib has a ViewDataExtensions class that allows you to get rid of magic strings in certain situations. It uses the Type as the key so you can get your object out of ViewData based on the Type and not some magic string. It works really well in certain situations. Just thought I'd pass it on to you guys.
Jeff T
A: 

I would make a base controller for all the controllers that will use your MasterPage. In that base controller I would load up your list of data to create the menu (from a cache, sql, whatever) and store it in ViewData.

If you want to you could also make a base model for all your models that will be loading your views based on the controller as well and then you could just load it directly into the models that extend this base class.

Assuming your went the easier ViewData route, in your user control you can just access the ViewData and load your menu since you can assume that all your contorllers will have pre-loaded this data.

Kelsey
Thank you, I don't know why I didn't do that from the start. Perhaps because I used to ride the short bus in high school.
Muad'Dib