0

I have CreateForm action in ProductController. This action uses view with model: ProductSupplierViewModel (consists of Product and List<Supplier> Suppliers).

In my CSHTML i have

@Html.LabelFor(m => m.Product.Supplier)
@Html.DropDownListFor(m => m.Product.Supplier.Id, new SelectList(Model.Suppliers, "Id", "Name"), "", new { @class = "form-control" })

BUT, this way i only have my default option set to blank (by using two quotation makrs in html helper).

What i need to know is:

  1. how to set a value="0" to that blank option?
  2. Does the web have default value if we dont specify one for it or?

Trying to get 0 because in my DataAccessLayer i have CreateProduct(Product p) method where i'll specify:

if(p.Supplier.Id == 0) // from parameter
{ 
  *put NULL value in this DB field*
}
Alex
  • 21
  • 10

1 Answers1

0

The most simple is:

@Html.DropDownListFor(m => m.Product.Supplier.Id, 
    new SelectList(Model.Suppliers, "Id", "Name", 0),
    "Please Select...",
    new { @class = "form-control" })

This creates a default item "Please Select...". However it's mandatory to select an item different than the default.

If selecting an item is not mandatory, you can do:

Controller

model.Suppliers.Insert(0, new Supplier()
{
    Id = 0,
    Name = "Please Select..."
});

View

@Html.DropDownListFor(m => m.Product.Supplier.Id, 
    new SelectList(Model.Suppliers, "Id", "Name", 0), 
    new { @class = "form-control" })
derloopkat
  • 6,232
  • 16
  • 38
  • 45