简体   繁体   中英

ASP.Net MVC Select List for Value Type

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM