[英]Do I need to pass data from the controller to the view in populating a dropdownlist?
我正在學習asp.net mvc,我剛開始,我決定從網絡表格轉移到mvc。
我只是很好奇,因為我有這個代碼,我想知道在return View(data)
傳遞模型與不傳遞它之間的區別。
這是代碼:
控制器
/* Even if I comment/remove the lines ViewBag.GenreId....... and ViewBag.ArtistId
and just return View(); everything seems to work fine. I'm following this music store tutorial from codeplex
*/
[HttpPost]
public ActionResult Create(Album album)
{
if (ModelState.IsValid)
{
db.Albums.Add(album);
db.SaveChanges();
return RedirectToAction("Index");
}
//this will assign the values of the dropdownlist of the View
//it will assign the values on the dropdownlist that has a name GenreId
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
return View(album);
}
觀點代碼
@model CodeplexMvcMusicStore.Models.Album
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Album</legend>
<div class="editor-label">
@Html.LabelFor(model => model.GenreId, "Genre")
</div>
<div class="editor-field">
@Html.DropDownList("GenreId", String.Empty)
@Html.ValidationMessageFor(model => model.GenreId)
</div>
我還想知道在View(album)
傳遞對象模型與傳遞View()
之間的區別。
據我所知,如果您沒有通過該模型,那么您的頁面將不會被填充。
此外,當您發布表單時,它也不知道將值綁定到何處。
如果您沒有傳遞數據,則無法訪問剃刀中的數據。 您需要將模型傳遞給return View(model)
才能在Razor View上使用它。 如果您需要傳遞多個模型,那么您可以使用ViewBag
或ViewData
來執行此操作。
通過查看你的問題。 在我看來,你可以在這個MVC DropDownListFor教程中找到你的答案
如果您沒有在返回View(相冊)中傳遞對象模型,則在視圖中不會顯示任何驗證錯誤(如果有)。 當您使用ViewBag for GenreId和ArtistId時,您可以在視圖中渲染而不會將對象模型傳遞給Karthik發布的視圖(返回View())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.