1

我目前正在学习 asp.net mvc,我刚开始,我决定从 web 表单转移到 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()

4

3 回答 3

2

据我所知,如果您不通过模型,那么您的页面将不会被填充。

此外,当您发回表单时,它也不知道将值绑定回哪里。

于 2013-01-08T09:48:39.920 回答
1

If you dont pass the data then you cannot access the data in the razor. You need to pass your model to the return View(model) in order to use it on the Razor View. If you need to pass more than one model then you can pass you use either ViewBag or ViewData to do this.

By looking at your question. It seems to me you might be able to find your answer in this MVC DropDownListFor tutorial

于 2013-01-08T12:26:19.430 回答
0

If you do not pass object model in return View(album) it will not show any validation errors in your view if there are any. As you are using ViewBag for GenreId and ArtistId you can render in view without passing the object model to view (return View()) posted by Karthik

于 2013-01-08T12:14:48.160 回答