Reputation: 3162
Can some one tell me why this bit of code
@Html.DropDownList("priority2", new SelectList(new[] { 1,2,3 }, Model.Priority))
gives me a fine dropdown to choose between 1,2,3
but this
@Html.DropDownList("priority", new SelectList(new [] {
new SelectListItem() { Value = "1", Text = "1. Priority" },
new SelectListItem() { Value = "2", Text = "2. Priority" },
new SelectListItem() { Value = "3", Text = "3. Priority" } },
Model.Priority))
gives me 3 options all saying 'System.Web.Mvc.SelectListItem'
What have I done wrong?
Upvotes: 1
Views: 1255
Reputation:
The SelectList()
constructor uses reflection to generate IEnumerable<SelectListItem>
. Where you do not specify the dataValueField
and dataTextField
properties, internally the method uses the .ToString()
value of the object in the collection.
In the first example, you have a an array of values types so .ToString()
outputs "1", "2" etc.
In the second example, you have an array of SelectListItem
and its .ToString()
method outputs "SelectListItem".
For the 2nd example to generate the correct html, it would need to be
@Html.DropDownList("priority", new SelectList(new []
{
new SelectListItem() { Value = "1", Text = "1. Priority" },
new SelectListItem() { Value = "2", Text = "2. Priority" },
new SelectListItem() { Value = "3", Text = "3. Priority" }
}, "Value", "Text", Model.Priority))
where the second parameter "Value"
specifies the property name of SelectListItem
to use for the value
attribute of the option, and the 3rd parameter "Text"
specifies the property to use for the options display text.
However, this is just pointless extra overhead (creating a 2nd SelectList
from the original SelectList
) and the last parameter Model.Priority
is ignored when binding to a property.
Instead the 2nd example can be simply
@Html.DropDownListFor(m => m.Priority, new []
{
new SelectListItem() { Value = "1", Text = "1. Priority" },
new SelectListItem() { Value = "2", Text = "2. Priority" },
new SelectListItem() { Value = "3", Text = "3. Priority" }
})
Upvotes: 1