2017-01-30 9 views
0

MVC APP를하고 있습니다. 두 개의 속성이있는 모델 호출 UserModel 상속보기가 있습니다. 사용자 이름과 비밀번호. 세션 변수에이 값을 저장하려고하므로 ModelBinder을 사용하고 있습니다.MVC 5 세션 변수 ModelBinder null on 작업 메서드

내 클래스 정의는 다음과 같습니다.

public class UserModel 
{ 
    public string UserName { get; set; } 
    public string Password { get; set; } 
} 

내 모델 바인더는 다음과 같습니다.

public class UserDetailModelBinder : IModelBinder 
{ 

    #region Constants 

    private const string SessionKey = "User"; 

    #endregion 


    #region Public Methods and Operators 

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     UserModel user = (controllerContext.HttpContext.Session != null) ? (controllerContext.HttpContext.Session[SessionKey] as UserModel) : null; 

     if (user == null) 
     { 
      user = new UserDetail(); 
      controllerContext.HttpContext.Session[SessionKey] = user; 
     } 

     return user; 
    } 

    #endregion 
} 

내가 내 Global.asax에

내가 찾은 문제에 제대로 정의는보기에서 UserModel 인스턴스를 받아 내 Action Method가 null 것입니다. 보기를 읽는 대신 내 세션을 이미 읽은 다음 세션에 저장합니다.

[HttpPost] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Login(UserModel model) 
{ 
} 

나는 모델 BinderModel를 사용하여보기에서 상속, 내가 세션에 저장할 수있는 방법, 그것이 내가 그래서, 내 질문이 될 것 BinderModel

에 저장 정의 된 동일 모델이기 때문에 그것이 생각?

답변

1

null 값을 UserModel로 설정하고 반환했습니다. 요청 값을 읽고 반환해야합니다.

var request = controllerContext.HttpContext.Request; 
    if (user == null) 
    { 
     user = new UserModel() { 
      UserName= request.Form.Get("UserName").ToString(), 

      Password = request.Form.Get("Password").ToString() 
     }; 

     controllerContext.HttpContext.Session["User"] = user; 
    } 

모델 바인더를 사용하는 대신 로그인 메소드에 세션에 사용자 모델을 직접 저장할 수 있습니다. 왜 모델 바인더를 선택하는지 모르겠습니다.

public async Task<ActionResult> Login(UserModel model) 
{ 
    //Session["User"] = model 
}