ASP.NET MVC dropdown-list from database

后端 未结 6 1465
梦如初夏
梦如初夏 2020-12-05 05:30

Ok, so I\'m new to this whole MVC-world, but it seems to be a pretty good way of getting things done and I\'m trying to make it work here.

The problem is: I can\'t g

6条回答
  •  囚心锁ツ
    2020-12-05 05:55

    I find this system works (and avoids using ViewBag):

    View Model:

    public class YourViewModel
    {
        // This could be string, int or Guid depending on what you need as the value
        public int YourDropdownSelectedValue { get; set; }
        public IEnumerable YourDropdownList { get; set; }
    }
    

    Controller:

    // Get database values (by whatever selection method is appropriate)
    var dbValues = db.YourEntity.ToList();
    
    // Make Selectlist, which is IEnumerable
    var yourDropdownList = new SelectList(dbValues.Select(item => new SelectListItem
    {
        Text = item.YourSelectedDbText,
        Value = item.YourSelectedDbValue
    }).ToList(), "Value", "Text");
    
    // Assign the Selectlist to the View Model   
    var viewModel = new YourViewModel(){
        // Optional: if you want a pre-selected value - remove this for no pre-selected value
        YourDropdownSelectedValue = dbValues.FirstOrDefault(),
        // The Dropdownlist values
        YourDropdownList = yourDropdownList
    };
    
    // return View with View Model
    return View(viewModel);
    

    and in the View:

    @Html.DropDownListFor(a => a.YourDropdownSelectedValue, Model.YourDropdownList, "select this text - change this to null to exclude", new { @class = "your-class" })
    

提交回复
热议问题