2012-09-03 3 views
2

_Layout.cshtml 및 _LogOnPartial.cshtml을 제공하는 새 프로젝트 템플릿에서 ASP MVC3을 사용하고 있습니다. _LogOnPartial에는 사용자가 로그인 할 때 표시되는 텍스트가 있습니다. 내 모델에서 내 자신의 추가 데이터를 표시하고 모든 뷰에 표시하려면 어떻게합니까?_LogonPartial에서 모델 데이터 표시

@if(Request.IsAuthenticated) { 
<text>Hello, <strong>@User.Identity.Name</strong>! - Account Balance: @Model.GetAccountBalance() 
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text> 
} 
else { 
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ] 
} 

답변

5

우리는 비슷한 정보를 갖고 Html.RenderAction()을 사용하여 실제로 계정 정보 상자를 표시합니다. 기본적으로, 그것은 아주 간단한 설치

레이아웃보기

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

뷰 모델

public class AccountInformation(){ 
    public bool IsAuthenticated {get;set;} 
    public string UserName {get;set;} 
    public int AccountBalance {get;set;} 
} 

계정 컨트롤러

public PartialViewResult Information(){ 
    var model = new AccountInformation(); 
    model.IsAutenticated = httpContext.User.Identity.IsAuthenticated; 
    if(model.IsAuthenticated){ 
     model.UserName = httpContext.User.Identity.Name; 
     model.AccountBalance = functionToGetAccountBalance(); 
     //Return the fully populated ViewModel 
     return this.PartialView(model); 
    } 
    //return the model with IsAuthenticated only set since none of the 
    //other properties are needed 
    return this.ParitalView(model); 
} 
에게 것3210

정보보기

@model AccountInformation 

@if(Model.IsAuthenticated) { 
<text>Hello, <strong>@Model.UserName</strong>! - Account Balance: @Model.AccountBalance 
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text> 
} 
else { 
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ] 
} 

이 작업은 몇 가지 일을하고 몇 가지 옵션

  1. HttpContext를 중심으로 도청하는 데에서보기를 유지

    에서 제공합니다. 컨트롤러가 그것을 처리하게하십시오.
  2. 이제 이것을 [OutputCache] 특성과 결합하여 Every로 렌더링 할 필요가 없습니다. 단일. 페이지.
  3. 계정 정보 화면에 더 많은 내용을 추가해야하는 경우 ViewModel을 업데이트하고 데이터를 채우는 것만 큼 간단합니다. 마술, 뷰백 없음 등
+0

간결한 답변에 감사드립니다. 문제 해결됨! – ChrisO

-2

당신은 뷰 모델이보기에 사용하고에 추가 데이터를 추가, 수정해야 :

는 여기에 내가 시도하지만 모델 데이터가 없기 때문에 당연히 작동하지 않는거야.