我是MVC的新手,我很难解决以下问题。一旦用户登录,我就通过Session["LoggedUserID"]
获得了一个userID。我想将它传递给以下cshtml代码(或直接在控制器中?),我目前还不明白。一旦用户想要创建新帖子,就会发生此操作。
在cshtml视图中(从Controller自动创建的代码):
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.CreatorUserId, "CreatorUserId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CreatorUserId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CreatorUserId, "", new { @class = "text-danger" })
</div>
</div>
我的控制器代码:
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Review review)
{
if (ModelState.IsValid) {
db.Reviews.Add(review);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(review);
}
如何将Session["LoggedUserID"]
传递给cshtml(或直接通过控制器)?查看表使用userID作为用户ID的FK。
编辑:我为当前代码获取的错误消息是:
没有类型为'IEnumerable'的ViewData项 有'CreatorUserId'键。
非常感谢任何帮助。感谢。
答案 0 :(得分:2)
如果用于保存实体,则无需将其传递给视图并将其发送回服务器。您可以直接在HttpPost操作方法中使用它。
[HttpPost]
public ActionResult Create(Review review)
{
if (ModelState.IsValid)
{
if(Session["LoggedUserID"]==null)
{
return Content("Session LoggedUserID is empty");
}
review.UserID = Convert.ToInt32(Session["LoggedUserID"]);
db.Reviews.Add(review);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(review);
}
我还添加了一个If条件,以便在将Session["LoggedInUserID"]
读取为int变量(UserID
属性)之前检查它是否为null。理想情况下,您可以将其移出操作方法以检查用户是否已登录(可能是操作过滤器like this)
答案 1 :(得分:1)
您需要绑定值,即“用户ID”以查看模型或将其放入视图包中,您可以在cshtml中访问它。
E.g。
SampleViewModel vm = new SampleViewModel(){UserId = yourvalue};
您需要使用名为SampleViewModel
的属性创建此UserId
类,然后您可以像这样使用。您需要将视图模型绑定到cshtml,例如 - @model SampleViewModel.cs
或者您可以将值存储在视图包中。 即
ViewBag.UserId = your-value; //You can call @ViewBag.UserId in cshtml page.
这有帮助吗?