- 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>
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.
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"); %>
精彩评论