Populate a dropdown list from db

五迷三道 提交于 2019-12-07 16:36:31

问题


I have an mvc 3 application with 2 tables in my entity framework.

PurchaseTable which was PurchaseID,PurchaseDate & ProductID I have another table called Product which contains ProductID and ProductName. creating a new view to insert a new purchase how do I change the textbox in the view for ProductID to be a dropdown bound by the ProductName in the Product table?


回答1:


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.




回答2:


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,



来源:https://stackoverflow.com/questions/4827243/populate-a-dropdown-list-from-db

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