You should not use the same name for the model property and the ViewBag
property (and ideally you should not be using ViewBag
at all, but rather a view model with a IEnumerable<SelectListItem>
property).
When using @Html.DropDownListFor(m => m.CustomerId, ....)
the first "Please Select"
option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem>
based on the one you have supplied in order to set the value of the Selected
property. In order to set the Selected
property, it reads the value of CustomerID
from ViewData
, and the first one it finds is "IEnumerable<SelectListItem>"
(not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).
When using @Html.DropDownList("CustomerId", ....)
, no data-val-*
attributes will be generated and you will not get any client side validation
Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag
property will it all work correctly.
CustomerID
- with OP's usage, there will be nodata-val-*
attributes generated and of the user selects the first "please select" option, no validation error will be displayed (when it should be - assumingCustomerID
is typeofint
) – KungCustomerID
is set in the controller (i.e. editing and existing entity), it will not selected correctly in the dropdownlist. – KungClientID
is set to 2 which matches the 2nd option, yet it is not selected in the view – Kung@Html.DropDownList("CustomerID", (SelectList)ViewBag.CustomerID, ....)
– KungDropDownList
if the names are different :) There are 2 ery good reason why you should never use the same nae for the model property and the view bag property. – KungCustomerID
from dropdown, better use:@Html.DropDownList("CustomerID", null, "please select")
– ZacharyDropDownList()
method. I'm adding an answer and will update the fiddle showing all use cases – Kung