通过ViewBag传递UserID

时间:2015-03-24 09:00:45

标签: asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

我正在尝试在创建操作中保存Identities UserID。

控制器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}

我做错了什么?

3 个答案:

答案 0 :(得分:2)

为什么不创建一个空的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)

答案 1 :(得分:1)

在我看来,根本不添加隐藏字段。在[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字段。

答案 2 :(得分:0)

您无法通过HTML帮助程序为强类型帮助程序分配值。

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

在您的视图中

创建如下代码。

@{
    model.RegUserID = ViewBag.RegUser;
}

然后创建一个隐藏的字段,如下所示。

@{
    @Html.HiddenFor(model => model.RegUserID)
}
相关问题