왜 당신이보기에 사용자 이름을 저장해야 할 : 기본 MVC2 프로젝트는 속성을 제공하기 위해 확장 할 수 있습니다 IMembershipService 인터페이스를 제공 할 것입니다? 아마도 당신이 컨테이너를 작성 고려해야하지 않으면
HttpContext.Current.User.Identity.Name
: 그것은 현재의 마지막 제안에 따라,는 MembershipProvider 사용에 로그인 한 사용자의 사용자 이름이 있다면, 그래서 당신은 확실히 컨트롤러 내에서 DB 트랜잭션을 시작합니다/래퍼 클래스를 명확하게 귀하의 뷰 모델을 나타냅니다 - 일부는 하나의 여분의 재산에 대한 과잉 고려할 수 있지만 코드에서 "마법의 문자열"이 싫어.
System.Web.Mvc.ViewPage<MyNamespace.MyView>
이 다음 예를 들어,보기에 모두를위한 강력한 형식의 속성을 가질 수 있습니다 :로
public class MyView
{
public string UserName { get; set; }
public MyObject MyMainObject { get; set;}
public MyView(string username, MyObject myMainObject)
{
this.Username = username;
this.MyMainObject = myMainObject;
}
}
다음 뷰 모델 유형을 설정
<%=Model.Username %>
<%=Model.MyMainObject.Title %>
대신하는 경우
public ActionResult(MyMainObject myMainObject, string username)
{
//Do something here
//if not correct
return View(new MyView(username, myMainObject));
}
당신이이 경로 아래로 가고 싶어으로 컨트롤러에 당신은 당신의 행동을 매개 변수화 할 수 있습니다
ViewData["Name"] = User.Identity.Name;
또는
ViewData.Add("Name", User.Identity.Name);
가 고려를 Enum을 만들어 다시 한번 피하십시오 g 문자열 리터럴
public enum UserEnum
{
Username,
Password
}
는 사용
ViewData.Add(UserEnum.Username.ToString(), User.Identity.Name);
출처
2010-11-20 00:37:38
Rob
시도하고 좀 더 설명 할 것이다. –
Rob은 내가 말하고자하는 답변에 대해 훨씬 자세히 설명했습니다. – neebz