I'm currently studying asp.net mvc and I just started, I decided to move away from web forms to mvc.
I'm just curious because I have this code and I want to know the difference between passing the model in the return View(data)
and not passing it.
Here's the code:
The Controller
/* 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);
}
The Code for the View
@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>
I would also like to know the difference between passing in the object model in View(album)
vs not passing it View()
.
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