Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a dropdown list from db

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?

like image 267
Diver Dan Avatar asked May 18 '26 17:05

Diver Dan


1 Answers

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.

like image 187
RPM1984 Avatar answered May 23 '26 12:05

RPM1984



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!