//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();
//in view
@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))
How can I make it so that by default it says "-Select Category-"
And validate to check something is selected (client and on the model)
Thanks
Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)
Models:
EmployeeReferral Controller:
View:
Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.
There is an overload with 3 arguments.
Html.DropdownList(name, selectList, optionLabel)
Update: there was a typo in the below code snippet.For the validator use
For ListBox / DropDown in MVC5 - i've found this to work for me sofar:
in Model:
in View:
I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:
and in your controller:
and then in your strongly typed view:
Also if you want client side validation don't forget to reference the necessary scripts: