0

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?

nche
  • 1,082
  • 3
  • 14
  • 32

1 Answers1

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.

lukiffer
  • 11,025
  • 8
  • 46
  • 70
  • Ok, i get it but, what controller do i do this in? I mean, it has to be done for every page that's called... and about the alternative, same question...7 – nche Apr 04 '11 at 07:40
  • How do you go about creating the custom attribute? What method should I be overiding? – nche Apr 04 '11 at 08:36
  • Here's an example of using custom attributes on View/Action results: http://stackoverflow.com/questions/1535535/custom-attributes-on-actionresult You can modify it to instead populate the necessary ViewData entries. – lukiffer Apr 05 '11 at 06:28