I want to create a DropDownList with a binding for one of my model data, but i want the dropdown items to be built within the View and i do not want the items coming in the Model data or from my controller. Can you please suggest how to build the selectlist within View
Basically I want to create something like this:
<%= Html.DropDownListFor(model=>model.SomeProperty,<<create the dropdown list items here>> %>
Please suggest.
-Sampat.
You can’t use it that way. As the name suggests its for returning an HTML select element for each property in the object that is represented by the specified expression using the specified list items and HTML attributes.
Though you can create this list object in view like following :-
Update
I will take the example of a Country Model with an Id/Name pair. Like following
Now, in your controller action, you can pass it as a selectlist:
And finally in View, you can use the DropDownListFor in the following manner.
On a Sidenote, if you just want to display a list of numbers with value, you can directly enter the HTML and utilize it, rather than using the DropDownListFor. Like follwing
Just make sure that “yourModelPropertyName” is correct and it should be the one for the property where you want it updated
More update
In the views where you wan’t to show the selected value, use below code
This shall do the trick 🙂