access database info in a partial view, .ascx that is included in Site.Master in asp.net mvc

不问归期 提交于 2019-12-12 05:28:36

问题


Hi i'm having problems with this. I am developing an asp.net mvc 2 application. I have a partial view menu.ascx defined. this gets included on all the pages of my site in the Site.Master masterpage. Now the thing is I want my menu to change according to the type of user. Here's what I did at first:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<% 
    ExtendedMemberShip.MemberShipUser user = ExtendedMemberShip.MemberShip.GetUser(HttpContext.Current.User.Identity.Name);
    string course = "Course/Index/";
    if(user != null) course += user.UserName;
%>
<% 
     if(user!=null && user.Type == "stud") { 
%>
         <li><%: Html.ActionLink("Courses", "Index", course)%></li>
<% 
      }
%>
<li><%: Html.ActionLink("Votes", "About", "Home")%></li>
<li><%: Html.ActionLink("Comments", "About", "Home")%></li>
<li><%: Html.ActionLink("Exam archives", "About", "Home")%></li>

The problem with this is that I shouldn't be doing this in the view ! But since this is the MasterPage no controller actually calls it so I don't know where to put the info in the ViewData dictionnary or ViewModel to pass it to this masterpage... any ideas?


回答1:


You can still do this in your controller. Populate your the relevant data into the ViewData dictionary:

public ActionResult Any()
{
    LoadUserType();
    return View();
}

private void LoadUserType()
{
    ExtendedMemberShip.MemberShipUser user = 
        ExtendedMemberShip.MemberShip.GetUser(HttpContext.Current.User.Identity.Name);
    ViewData["UserType"] = user.Type;
}

In your master page use:

<% Html.RenderPartial("Menu", ViewData["UserType"]) %>

You could avoid having to call LoadUserType() or whatever by creating a Custom Attribute that did that for you, or putting it in a base class that all of your controllers extended.

Alternatively, you could just populate the menu items as part of the Model and pass the Model to the PartialView.



来源:https://stackoverflow.com/questions/5521466/access-database-info-in-a-partial-view-ascx-that-is-included-in-site-master-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!