I am trying to create a dropdonw in my MVC web application.
Model
namespace projectname.Models
{
public class DropDownModel
{
public int i
There are a few ways of display DropDownList in MVC. Here is my way.
Note: You need a collection of SelectListItem in model.
public class MyModel
{
public int SelectedId { get; set; }
public IList AllItems { get; set; }
public MyModel()
{
AllItems = new List();
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel();
model.AllItems = new List
{
new SelectListItem { Text = "One", Value = "1"},
new SelectListItem { Text = "Two", Value = "2"},
new SelectListItem { Text = "Three", Value = "3"}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Get the selected value
int id = model.SelectedId;
return View();
}
}
@model DemoMvc.Controllers.MyModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownListFor(x => x.SelectedId, Model.AllItems)
}