How to use DropDownListFor
I want to add a Drop Down List html control to a web page to populate it with a list of products. My Action controller looks like
public ActionResult Index()
{
return View(_repository.GetProducts(true));
}
Product Model (Linq to SQL, below is incomplete class where SelectedId is for dropdown selection id)
public partial class Product
{
public int SelectedId { get; set; }
}
View
@model IQueryable<Entity.Product> @Html.DropDownListFor(.....)
What I don't understand is how to populate the DropDownList with Products and if the selected product binds the Id property to the SelectedId.
source to share
You can implement it like this:
In your model, you need something like this
public class TestViewModel
{
public int IdSelected { get; set; }
public IEnumerable<Person> People { get; set; }
}
In your controller you need something like this
public ActionResult Index()
{
var people = new List<Person>
{
new Person {Id = 1, Name = "krystan"},
new Person {Id = 2, Name = "Bobby"}
};
var theModel = new TestViewModel
{
People = people.Select(x => new Person
{
Id = x.Id,
Name = x.Name
})
};
return View(theModel);
}
Then in your html (and it depends a little on the view engine used, but allows a razor) you need something like this
@model MvcApplication3.Models.TestViewModel
@Html.DropDownListFor(x=>x.IdSelected, new SelectList(Model.People, "Id", "Name"))
More information can be found on this website
source to share
Define the view model:
public class MyViewModel
{
public int SelectedId { get; set; }
public IEnumerable<Product> Products { get; set; }
}
Your controller action has this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
Products = _repository.GetProducts(true)
}
return View(model);
}
and in your view, use the view model to create the dropdown:
@model MyViewModel
@Html.DropDownListFor(
x => x.SelectedId,
new SelectList(Model.Products, "ProductId", "ProductName")
)
where ProductId
and ProductName
is obviously 2 properties of your domain model Product
that will be used to bind the value and text of each <option>
in the dropdown.
source to share
1) Create a function that will return IEnumerbale List of SelecteListItem as shown below
public IEnumerable<SelectListItem> GetProducts()
{
List<Product> ProductList = new List<Product>();
//Here linq query to fetch products
return ProductList.Select(c => new SelectListItem
{
Value = c.Id,
Text = c.ProductName //Or whatever you want to display
});
}
2) Store in view mode in controller methods
public ActionResult Index()
{
ViewBag.ProductList = GetProducts()
return View();
}
3) Bind it in the target view as below
@Html.DropDownList("Id", (IEnumerable<SelectListItem>)ViewBag.ProductList, "--Select--")
The Id element above uses the Model element that you will use to bind this view, and consider the value element to store data and "--Select--" is used for the default value.
source to share