Question

I'm new to MVC and I'm having trouble understanding a piece of code. I created a new controller and with it all the CRUD methods and view - auto-generated by visual studio - and I could not understand one part of the code.

See, in the controller it set a SelectList from the database and put it in a ViewBag like this: Controller

public ActionResult Create()
{    
    ViewBag.TypeID = new SelectList(db.PlacementTypes, "TypeID", "Description");
    return View();
} 

And in the View it's like this:

<div class="editor-label">
    @Html.LabelFor(model => model.TypeID, "PlacementType")
</div>
<div class="editor-field">
    @Html.DropDownList("TypeID", String.Empty)
    @Html.ValidationMessageFor(model => model.TypeID)
</div>

What I don't understand is. Where the heck is the SelectList comming from? Since I don't see a call to ViewBag.

I would expect something like:

@Html.DropDownListFor("TypeID", (SelectList)ViewBag.TypeID)

That's my doubt. How does MVC know where to find the right list without specifying the ViewBag??

Was it helpful?

Solution 2

FACTS:



In your example you dont have to cast the SelectList ViewBag since ViewBag is a dynamic type.

The SelectList part function of TypeID was already been done on your Controller part.
So calling the TypeID alone on your create will already trigger everything that is under to it.

OTHER TIPS

Since you have named your DropDownList "TypeID" since there was no SelectList provided the code will search the Model for an item called "TypeID".

Therefore the call to ViewBag.TypeID to get the SelectList is happening behind the scenes.

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