Strongly-typed binding to a DropDownListFor?

前端 未结 4 1416
盖世英雄少女心
盖世英雄少女心 2021-01-05 03:34

Normally I would bind data to a DropDownListFor with a SelectList:

@Html.DropDownListFor(model => model.CustomerId, new SelectLi         


        
4条回答
  •  情深已故
    2021-01-05 03:54

    You could create the select list itself in the controller and assign it to a property in your view model:

    public IEnumerable OrdersList { get; set; }
    

    The code in your controller will look like this:

    model.OrdersList = db.Orders
                         .Select(o => new SelectListItem { Value = o.OrderId, Text = o.ItemName })
                         .ToList();
    

    In the view you can use it like this:

    @Html.DropDownListFor(model => model.CustomerId, Model.OrderList)
    

    I personally prefer this approach since it reduces logic in your views. It also keeps your logic 'stronly-typed', no magic strings anywhere.

提交回复
热议问题