Question

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().

Was it helpful?

Solution 3

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

OTHER TIPS

As far as I am aware, if you do not pass the model through then your page will not be populated.

Also it will not know where to bind the values back to when you post the form back.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top