I have list of items in table with 3 columns. This is asp.net MVC3 razor scaffholding list. I want to display this list as drop down items list. Is there any option to display list in dropdown? If this is not possible I am planning to show hide this
div on a textbox click. Please suggest me any good approach for this
public class ItemCreateViewModel
{
public int ItemID { get; set; }
public List<Item> Items{ get; set; }
}
In your view:
@Html.DropDownListFor(
x => x.ItemID,
new SelectList(Model.Items, "ID", "Name"))
@Html.ValidationMessageFor(model => model.ItemID)
X.ItemID specifies which property the value gets assigned to by the binder. In this case, we want the selected value to map to the ItemID property of our viewModel class. new SelectList() takes 3 parameters:
The list to create a dropdown from
The column name to use as the "value"
The column to use as the "text"
You need to fill the viewModel within your controller before sending the viewModel to your view:
public ActionResult Create()
{
var viewModel = new ItemCreateViewModel
{
Items = db.Items.ToList();
};
return View(viewModel);
}
chandrasheka...
Member
5 Points
47 Posts
razor list as dropdown with selection
Dec 28, 2012 06:00 PM|LINK
I have list of items in table with 3 columns. This is asp.net MVC3 razor scaffholding list. I want to display this list as drop down items list. Is there any option to display list in dropdown? If this is not possible I am planning to show hide this div on a textbox click. Please suggest me any good approach for this
mgasparel
Member
298 Points
65 Posts
Re: razor list as dropdown with selection
Dec 28, 2012 06:31 PM|LINK
In your viewModel:
public class ItemCreateViewModel { public int ItemID { get; set; } public List<Item> Items{ get; set; } }In your view:
@Html.DropDownListFor( x => x.ItemID, new SelectList(Model.Items, "ID", "Name")) @Html.ValidationMessageFor(model => model.ItemID)X.ItemID specifies which property the value gets assigned to by the binder. In this case, we want the selected value to map to the ItemID property of our viewModel class.
new SelectList() takes 3 parameters:
You need to fill the viewModel within your controller before sending the viewModel to your view:
public ActionResult Create() { var viewModel = new ItemCreateViewModel { Items = db.Items.ToList(); }; return View(viewModel); }