ASP.NET MVC Select List for Value Type

I am trying to do the simplest thing with a drop down list and it just doesn't work. I have an integer property called SearchCriteria.Distance. This is a simple integer property. I am trying to associate this property with a drowpdown list of integers, but it will not bind. Value is always 0. Here is 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 is a simple list of integers, there is not Text Valueto associate it with. What am I doing wrong here?

Change . It turns out that this problem was the result of a stupid mistake on my part. I had a hidden field with an identifier SearchCriteria.Distancein my form, which I forgot about, which did not allow setting the drop down value. I called this solution below because it is correct.

+5
source share
1 answer

The example below will hopefully be 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 the model (create the "ViewModels" folder for your view models, this file will be located 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)
+6
source

All Articles