问题
Still trying to get to grips to the new SimpleMembership with MVC4. I changed the model to include Forename and Surname which works fine.
I want to change the information displayed when logged in so instead of using User.Identity.Name in the View I want to do something like User.Identity.Forename, what's the best way to accomplish this?
回答1:
Yon can leverage @Html.RenderAction()
feature available in ASP.NET MVC to display this kind of info.
_Layout.cshtml View
@{Html.RenderAction("UserInfo", "Account");}
View Model
public class UserInfo
{
public bool IsAuthenticated {get;set;}
public string ForeName {get;set;}
}
Account Controller
public PartialViewResult UserInfo()
{
var model = new UserInfo();
model.IsAutenticated = httpContext.User.Identity.IsAuthenticated;
if(model.IsAuthenticated)
{
// Hit the database and retrieve the Forename
model.ForeName = Database.Users.Single(u => u.UserName == httpContext.User.Identity.UserName).ForeName;
//Return populated ViewModel
return this.PartialView(model);
}
//return the model with IsAuthenticated only
return this.PartialView(model);
}
UserInfo View
@model UserInfo
@if(Model.IsAuthenticated)
{
<text>Hello, <strong>@Model.ForeName</strong>!
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]
</text>
}
else
{
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
This does a few things and brings in some options:
- Keeps your view from having to sniff around the HttpContext. Let's the controller deal with that.
- You can now combine this with an [OutputCache] attribute so you don't have to render it in every single page.
- If you need to add more stuff to the UserInfo screen, it is as simple as updating the ViewModel and populating the data. No magic, no ViewBag, etc.
来源:https://stackoverflow.com/questions/12572819/getting-user-information-using-simplemembership