Reputation: 46591
On my home page I have a search form where people can search for houses. It redirects to a controller and action which searches for houses and shows them in a View.
On the result View I have a several lists like this.
<select name="priceFrom">
<option value="0">€0</option>
<option value="100000">€100.000</option>
<option value="200000">€200.000</option>
</select>
The View contains a model: @model Irrelevant.Namespace.ViewModels.SearchResults
I want to select the value they chose on the home page, it's stored in the SearchResults ViewModel. In WebForms I used to do Bind()
or Eval()
, is there any equivalent in MVC which offers a clean way to accomplish this?
Upvotes: 1
Views: 309
Reputation: 8980
you have to do the below for all the options
<select name="priceFrom">
<option value="0" @(Model.PriceFrom.ToString().Equals("0") ? "selected":"")>€0</option>
<option value="100000" @(Model.PriceFrom.ToString().Equals("100000") ? "selected":"")>€100.000</option>
...
</select>
There is one more way in MVC that can take advantage of @Html.DropDownListFor
method where you need to have a list property in your model that can be directly bind to the Dropdownlist with the specified selected value
Upvotes: 2
Reputation: 54387
SelectListItem
has a Selected
property, which will be respected by Html.DropDownListFor<>()
.
If you are manually declaring the markup for your selects
, you end up with a functional but much less elegant solution, such as:
<select name="priceFrom">
<option value="0">€0</option>
<option value="100000" @(Model.SomeCondition ? "selected" : "" )>€100.000</option>
<option value="200000" @(Model.SomeCondition ? "selected" : "" )>€200.000</option>
</select>
Remember, the presence of the selected
attribute may cause the user agent to treat is as "true".
Ideally, all of your dropdown lists would be generated from your view model. When your view model is created, you would evaluate previous conditions (such as a selection on another page) and set Selected
on the appropriate item.
Upvotes: 2