[英]How to pass Data from Controller to View with IEnumerable Model in MVC?
[英]How to pass Session data from controller to View (MVC)
我是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作為FK作為用戶ID。
編輯:我為當前代碼得到的錯誤消息是:
沒有類型為“ IEnumerable”的ViewData項目具有鍵“ CreatorUserId”。
任何幫助深表感謝。 謝謝。
如果用於保存實體,則無需將其傳遞到視圖並將其發送回服務器。 您可以在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。 理想情況下,你可以移動了這一點的操作方法來檢查用戶是否登錄或沒有(可能是一個動作過濾器這樣的 )
您需要綁定值即“用戶ID”以查看模型或將其放在視圖包中,然后可以在cshtml中訪問它。
例如
SampleViewModel vm = new SampleViewModel(){UserId = yourvalue};
您需要使用一個名為UserId
的屬性來創建此SampleViewModel
類,然后可以像這樣使用。 您還需要將視圖模型綁定到您的cshtml,就像- @model SampleViewModel.cs
或者您可以將值存儲在查看包中。 即
ViewBag.UserId = your-value; //You can call @ViewBag.UserId in cshtml page.
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.