【发布时间】:2016-09-26 18:08:26
【问题描述】:
我是 MVC 的新手,我很难解决以下问题。我通过Session["LoggedUserID"] 获得了一个用户ID,因为它在用户登录后获得。我想将它传递给我目前不明白的以下cshtml代码(或直接在控制器中?)。一旦用户想要创建新帖子,就会发生此操作。
cshtml 视图内部(从控制器自动创建的代码):
@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(或直接通过控制器)? Review 表使用 userID 作为用户 ID 的 FK。
编辑:我当前代码收到的错误消息是:
没有“IEnumerable”类型的 ViewData 项 有键 'CreatorUserId'。
非常感谢任何帮助。谢谢。
【问题讨论】:
-
可以在控制器中访问会话,所以不清楚实际问题是什么。
-
或stackoverflow.com/questions/18608452/… ... 真的不清楚您有什么问题(可能是因为您不了解 ASP.Net MVC 的工作原理或 Session 的工作原理)。
-
你的意思是“将会话传递给 Cshtml”?您想通过以便可以在标签中显示它吗?或者是其他东西 ?你必须清楚你在做什么。此外,您当前的代码正在使用 DropDownList 辅助方法,我没有看到在您的 GET 操作中设置任何 ViewData 来填充下拉列表(这就是您收到“没有 ViewData ....”错误消息的原因!跨度>
-
@skylake 查看我发布的答案
标签: c# asp.net-mvc razor database-first