2012-09-24 2 views
4

MVC4를 사용하여 새로운 SimpleMembership에 대한 정보를 얻으려고합니다. Forename과 성을 포함하도록 모델을 변경했습니다.SimpleMembership을 사용하여 사용자 정보 가져 오기

User.Identity.Name 대신 User.Identity.Forename과 같은 작업을 수행하려는보기에서 로그인 할 때 표시되는 정보를 변경하고 싶습니다.이를 수행하는 가장 좋은 방법은 무엇입니까?

답변

5

Yon은 이러한 종류의 정보를 표시하기 위해 ASP.NET MVC에서 사용할 수있는 @Html.RenderAction() 기능을 활용할 수 있습니다.

_Layout.cshtml보기

@{Html.RenderAction("UserInfo", "Account");} 

보기 모델

public class UserInfo 
{ 
    public bool IsAuthenticated {get;set;} 
    public string ForeName {get;set;} 
} 

계정 컨트롤러

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

사용자 정보보기 몇 가지 옵션에

@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") ] 
} 

이 몇 가지 일을하고 가져가 :

  1. 는 HttpContext를 중심으로 도청 할 필요가보기를 유지합니다. 제어기가 그 문제를 해결합시다.
  2. 이제이 값을 [OutputCache] 속성과 결합하여 모든 단일 페이지에서 렌더링 할 필요가 없습니다.
  3. UserInfo 화면에 더 많은 내용을 추가해야하는 경우 ViewModel을 업데이트하고 데이터를 채우는 것만 큼 간단합니다. 마술이나 뷰백 등이 없습니다.
관련 문제