I'm trying to do the simplest thing with an dropdown and it's just not working. I have a an integer property called SearchCriteria.Distance
. It's a simple integer property. I'm trying to bind that property to a drowpdown list of integers but it will not bind. The value is always 0
. Here's the code:
@Html.LabelFor(x => x.SearchCriteria.Distance, "Radius (miles)", new { @class="control-label" })
<div class="controls">
@Html.DropDownListFor(x => x.SearchCriteria.Distance, new SelectList(new int[] { 5, 15, 25, 50 }), new { @class="input-small", style="height:36px;"})
</div>
Because it's a simple integer list, there's not Text
Value
to associate it with. What am I doing wrong here?
Edit: Turns out this problem was the result of a stupid error on my part. I had a hidden field with the SearchCriteria.Distance
id on my form that I forgot about that prevented the drop down value from being set. I marked the solution below as the answer because it is correct.
SelectList(IEnumerable, String, String, Object, IEnumerable) Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, the selected value, and the disabled values. SelectList(IEnumerable, String, String, String, Object)
The example below should hopefully work enough for you to get an idea...
Controller ('/Controllers/TestController.cs' for this example):
public class TestController : Controller
{
public ActionResult MyForm()
{
SearchViewModel model =
new SearchViewModel()
{
Distance = 5 // This is the item that will be selected.
};
return View(model);
}
}
View model (create a 'ViewModels' folder for your view models, this file would live in '/ViewModels/SearchViewModel.cs'):
public class SearchViewModel()
{
public int Distance { get; set; }
public IEnumerable<SelectListItem> DistanceItems
{
get
{
List<int> distances = new List<int>() { 5, 15, 25, 50 };
return distances.Select(d => new SelectListItem() { Text = i.ToString(), Value = i.ToString() });
}
}
}
View ('/Views/Test/MyForm.cshtml'):
@model MvcApplication1.ViewModels.SearchViewModel
@Html.DropDownListFor(m => m.Distance, Model.DistanceItems)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With