Action 方法上的 MVC 5 会话变量 ModelBinder 为空

MVC 5 Session Variable ModelBinder null on Action Method

我正在做一个MVC APP。我有一个从具有 2 个属性的模型调用 UserModel 继承的视图。用户名和密码。我想将这些值保存在会话变量中,所以我使用 ModelBinder.

我的class定义是这样的

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

中正确定义了

我发现的问题是我的 Action Method 从 View 接收一个 UserModel 实例是空的。它读取已经有我的会话而不是读取视图,然后将其保存在会话中。

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

我想这是因为它与我定义的保存在 BinderModel

中的模型相同

所以,我的问题是,如何在 Session 中保存一个使用 BinderModel 从 View 继承的模型?

您正在将空值设置为 UserModel 并 returned。您应该从请求和 return 中读取值。

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
}