rem*_*rem 3 asp.net-mvc user-controls master-pages
以下是Visual Studio(LogOnUserControl.ascx)创建的标准默认ASP.NET MVC项目中的LogOn用户控件:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
if (Request.IsAuthenticated) {
%>
Welcome <b><%: Page.User.Identity.Name %></b>!
[ <%: Html.ActionLink("Log Off", "LogOff", "Account") %> ]
<%
}
else {
%>
[ <%: Html.ActionLink("Log On", "LogOn", "Account")%> ]
<%
}
%>
Run Code Online (Sandbox Code Playgroud)
它被插入到母版页中:
<div id="logindisplay">
<% Html.RenderPartial("LogOnUserControl"); %>
</div>
Run Code Online (Sandbox Code Playgroud)
该<%: Page.User.Identity.Name %>代码显示的登录名的用户,当前登录的.
如何显示用户FirstName而不是保存在配置文件中?
我们可以在如下控制器中读取它:
ViewData["FirstName"] = AccountProfile.CurrentUser.FirstName;
Run Code Online (Sandbox Code Playgroud)
例如,如果我们尝试这样做:
<%: ViewData["FirstName"] %>
Run Code Online (Sandbox Code Playgroud)
它仅在控制器调用的页面上呈现,其中 ViewData["FirstName"]值已分配.
jim*_*lan 11
雷姆
这是其中一种情况,其中有一个基本控制器可以解决你的所有问题(好吧,有些人).在你的基本控制器中,你有类似的东西:
public abstract partial class BaseController : Controller
{
// other stuff omitted
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
ViewData["FirstName"] = AccountProfile.CurrentUser.FirstName;
base.OnActionExecuted(filterContext);
}
}
Run Code Online (Sandbox Code Playgroud)
并在所有控制器中使用它,如:
public partial class MyController : BaseController
{
// usual stuff
}
Run Code Online (Sandbox Code Playgroud)
或类似的.然后,您可以随时将其用于所有控制器的每个操作.
看看它是否适合你.