如何传递未在视图中分配的用户 ID>MVC5 中来自控制器的模型

How to pass User ID which is not assigned in view>Model from Controller in MVC5

那是我的 Change Pass ViewModel。

public class ChangePasswordViewModel
{
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Current password")]
    public string OldPassword { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm new password")]
    [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

然后我使用这样的登录 ID 将操作重定向到 ChangePass 控制器 >>

return RedirectToAction("ChangePassword", new { id = loginuser[0].PkUserAcc });

在我的 Change Pass get 方法中 >>

public ActionResult ChangePassword(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    tblUserAcc tbluseracc = db.tblUserAccs.Find(id);
    if (tbluseracc == null)
    {
        return HttpNotFound();
    }
    else
    {
        return View();
    }
}

我在 ChangePassword 视图中使用了 ChangePasswordViewModel>>

@model IBS.Models.ChangePasswordViewModel

URL 那样>>

http://localhost:63855/User/ChangePassword/2

我的问题是>>

  1. 我可以从 Post 方法获取 LoginID (2) 吗?

  2. 查看表单ChangePass(get方法)需要传递LoginID,如何传递?

你可以使用 Viewbag

首先在您的控制器中设置。

..
ViewBag.LoginID  = tbluseracc.Id;
return View();

在你看来

...
<input id="loginId" type="hidden" value="@ViewBag.LoginID"/> 

从那时起你可以在你的 post 方法中再次传递它..

为您的模型添加一个 属性 作为 ID

public class ChangePasswordViewModel
{
  public int ID { get; set; } // add this
  [Required]
  [DataType(DataType.Password)]
  [Display(Name = "Current password")]
  public string OldPassword { get; set; }

然后在你的 GET 方法中

public ActionResult ChangePassword(int? id)
{
  if (id == null)
  {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  }
  tblUserAcc tbluseracc = db.tblUserAccs.Find(id);
  if (tbluseracc == null)
  {
      return HttpNotFound();
  }
  ChangePasswordViewModel model = new ChangePasswordViewModel();
  model.ID = id;
  return View(model);
}

如果您有带 defaults: new { controller = "..", action = "..", id = UrlParameter.Optional } 的默认路由,那么 ID 将被添加到路由值中,并且当您 post 返回时,模型将与 ID 绑定。如果不是,则需要为该值添加隐藏输入(或将其添加到路由值)