asp.net mvc3 working with master pages
In my website, when the user logs in, I want to show the user name and also show a logout button.
In ASP.NET 4.0, we could use the code behind file of the master page to write code for a common thing like this. But I don't know how to achieve this in MVC3. I would not like to pass user name on every page view and add action link of logou开发者_JAVA百科t on every controller.
Can anyone suggest a better way?
Thanks
Saarthak
You could use a partial. The default template does exactly that. Create a new ASP.NET MVC 3 application using the built-in wizard and look at the _LogOnPartial.cshtml
partial that's been generated for you and which is invoked in the _Layout.cshtml
using @Html.Partial("_LogOnPartial")
.
This partial looks like this:
@if(Request.IsAuthenticated) {
<text>Welcome <strong>@User.Identity.Name</strong>!
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
It checks if the user is authenticated and if it is it Welcomes him and provides a LogOff link and if he isn't it simply provides a LogOn link.
Same stuff if you are using the WebForms view engine:
LogOnUserControl.ascx
which is invoked from Site.Master
using <% Html.RenderPartial("LogOnUserControl"); %>
.
精彩评论