通过 ViewBag 传递 UserID

Passing UserID through a ViewBag

我正在尝试在创建操作中保存身份用户 ID。

控制器GET请求如下:

// GET: Owners/Create
public ActionResult Create()
{
    ViewBag.RegUser = User.Identity.GetUserId();
    return View();
}

查看如下:

@Html.HiddenFor(model => model.RegUserID, new { @value = ViewBag.RegUser })

控制器POST请求如下:

// POST: Owners/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OwnerID,OwnerName,ContactName,PhysicalAddress1,PhysicalAddress2,PhysicalCity,PhysicalState,PhysicalCountry,PhysicalPostCode,PostalAddress1,PostalAddress2,PostalCity,PostalState,PostalCountry,PostalPostCode,Phone,Mobile,Fax,Email,RegUserID")] Owner owner)
{
    if (ModelState.IsValid)
    {
        db.Owners.Add(owner);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(owner);
}

但是当保存记录时,RegUserID 为空。

如果我在 @Html Helper 上中断,值被分配给 model.RegUserID 我可以在视图中看到 UserID:

ViewBag.RegUser "7318611e-7e2e-4ee2-9c7b-51b20f0806d8"  dynamic {string}

我做错了什么?

为什么不直接创建一个空的 Owner 对象并在 get 方法中发送,而不是像这样在 ViewBag 中传递它:

// GET: Owners/Create
public ActionResult Create()
{
    Owner owner = new Owner();
    owner.RegUserId = User.Identity.GetUserId();
    return View(owner);
}

查看如下:

@Html.HiddenFor(model => model.RegUserID)

您无法通过 HTML 助手为强类型助手赋值。

注意:您必须将值分配给您属性,然后将其用作隐藏字段。示例如下。

在您看来,创建如下代码。

@{
    model.RegUserID = ViewBag.RegUser;
}

然后像下面这样创建一个隐藏字段。

@{
    @Html.HiddenFor(model => model.RegUserID)
}

我认为根本不要添加隐藏字段。在 [HttpPost] Create 中,您可以像在 [HttpGet] Create.

中访问它一样访问它
// GET: Owners/Create
public ActionResult Create()
{
    return View();
}

// remove RegUserID from Bind Include
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OwnerID,OwnerName,ContactName,PhysicalAddress1,PhysicalAddress2,PhysicalCity,PhysicalState,PhysicalCountry,PhysicalPostCode,PostalAddress1,PostalAddress2,PostalCity,PostalState,PostalCountry,PostalPostCode,Phone,Mobile,Fax,Email")] Owner owner)
{
    if (ModelState.IsValid)
    {
        owner.RegUser = User.Identity.GetUserId();
        db.Owners.Add(owner);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(owner);
}

像这个客户端不能改变那个RegUserID字段。