Fill out the dropdown from db

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

PurchaseTable, which was PurchaseID, PurchaseDate, and ProductID I have another table called Product that contains ProductID and ProductName. When creating a new view to insert a new purchase, how do I change the text box in the view for ProductID as a dropdown restriction on ProductName in the Product table?

+3
source share
2 answers

Create ViewModel:

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

Customizing a view using 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 just snap to the ViewModel and use the DropDownListFor HTML Helper:

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

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

, , SelectedProductId .

+6

, . :

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

- ( "" ), - "id", (, SelectedValue), - "", , - .

, MyTablesDB, :

MyTablesDB db = new MyTablesDB();

:

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

,

+3

Source: https://habr.com/ru/post/1788454/


All Articles