【问题标题】:How do I edit a FormCollection value, and then use TryUpdateModel with the edited collection?如何编辑 FormCollection 值,然后将 TryUpdateModel 与编辑后的集合一起使用?
【发布时间】:2015-04-09 22:30:54
【问题描述】:

MVC5 以明文形式存储我的密码。我不想使用默认的散列算法,因为我需要改用e.Encrypt()。我正在创建一个注册函数,在使用TryUpdateModel 之前,我需要知道如何编辑来自FormCollection 的值。

代码如下:

    [HttpPost]
    public ActionResult Register([Bind(Include = "User,Pass,Email")] FormCollection form)
    {
        var user = new Users();
        string Hash = e.Encrypt(form["Pass"]); // Gets set.
        if (TryUpdateModel(user, form))
        {
            context.Entry(user).State = EntityState.Added;
            context.SaveChanges();
            return RedirectToAction("Login", "Account");
        }
        return View();
    }

我从高处到低处都找遍了,我找到的一切都与我的需求无关。

我试过这个:

form["Password"] = e.Encrypt(form["Password"])

...并且可以编译,但是在调试时,该值永远不会被设置。 e.Encrypt() 确实是一个函数,所以不是这样。

我做错了什么?

【问题讨论】:

  • 使用模型绑定和强类型模型而不是FormCollection
  • 能否将您的评论建议转换成代码?谢谢。

标签: c# asp.net-mvc-5 entity-framework-6


【解决方案1】:

经过反复试验,我想通了:

    [HttpPost]
    // Remove FormCollection and replace with UserModel.
    public ActionResult Register([Bind(Include= "Username,Password,EmailAddress")] UserModel user)
    {
        if (TryUpdateModel(user))
        {
            // Set password in TryUpdate success.
            user.Password = e.Encrypt(user.Password);; // Set correctly

            context.Entry(user).State = EntityState.Added;
            context.SaveChanges();
            return RedirectToAction("Login", "Account");
        }
        return View();
    }

然而,另一个问题出现了,DataValidationError。问题来自UserModel.cs 类:

    [RegularExpression(RegexPassword, ErrorMessage = ErrorPassword)]

我有一个与哈希不匹配的正则表达式,所以当我尝试更新时,它无法验证。这是另一个线程的问题,但我现在只是将其删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多