在局部视图访问数据库信息,的.ascx包含在中的Site.Master asp.net的MVC [英] access database info in a partial view, .ascx that is included in Site.Master in asp.net mvc

查看:128
本文介绍了在局部视图访问数据库信息,的.ascx包含在中的Site.Master asp.net的MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是有这个问题。我开发一个asp.net MVC 2的应用程序。我有一个局部视图menu.ascx定义。这个被列入了母版的Site.Master的我的网站的所有网页。现在的事情是我希望我的菜单根据用户类型而改变。
下面是我在做第一次:

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>

这样做的问题是,我不应该在视图中这样做!但由于这是没有实际控制调用它的母版,所以我不知道在哪里把信息在ViewData的dictionnary或视图模型将它传递给该母版...
任何想法?

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?

推荐答案

您仍然可以做到这一点在你的控制器。填充您的相关数据到ViewData字典:

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;
}

在你的母版页使用:

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

您可以避免不必调用 LoadUserType()或任何通过创建做了一个自定义属性,对你,还是把它放在一个基类,所有的控制器延长。

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.

另外,你可以只填充菜单项作为模型的一部分​​,模型传递到PartialView。

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

这篇关于在局部视图访问数据库信息,的.ascx包含在中的Site.Master asp.net的MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆