Populate a dropdown list from db

独自空忆成欢 提交于 2019-12-05 21:11:47

Create a ViewModel:

public class CreatePurchaseViewModel
{
   public Purchase Purchase { get; set; }
   public IEnumerable<SelectListItem> Products { get; set; }
   public int SelectedProductId { get; set; }
}

Setup the View with the ViewModel:

[HttpGet]
public ActionResult CreateProduct()
{
   var model = new CreatePurchaseViewModel
   {
      Products = repository.FindAllProducts().Select(x =>
              new SelectListItem
              {
                  Text = x.ProductName,
                  Value = x.ProductId
              }
   };

   return View(model);
}

Then simply bind to the ViewModel and use the DropDownListFor HTML Helper:

<! -- other code to bind to Purchase, and then: -->

<%= Html.DropDownListFor(x => x.SelectedProductId, Model.Products) %>

Then when you submit the form, the SelectedProductId value in the model will be populated with the selected value from the dropdown list.

Jerry Elizondo

The answer is easier than it looks. Simply create a list:

myDropDown = new SelectList(db.Products, "Product_ID", "ProductName", idSelected);

The first parameter is your table ("Products" from the Entity Model), the second is the "id" that will be returned when selecting from the list (i.e SelectedValue), the third is the "text" that will be displayed in the list and the last parameter is the currently selected item.

Assuming your model is called MyTablesDB, then:

MyTablesDB db = new MyTablesDB();

For example:

public SelectList GetPullDown(object idSelected) {
    myTablesDB myDB = new MyTablesDB();
    return new SelectList(myDB.Products, "Product_ID", "Product_Name", idSelected);
}

Cheers,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!