MVC5 view drop down list

天大地大妈咪最大 提交于 2019-12-03 09:03:19

Model :

 public List<SelectListItem> mapLocationItemTypes { get; set; }
 public int mapLocationItemVal { get; set; }

View:

@Html.DropDownListFor(m => m.mapLocationItemVal , new SelectList(Model.mapLocationItemTypes , "Value", "Text"), "  -----Select List-----  ")

here in above example the 3rd parameter of DropDownListFor() i.e. " -----Select List----- " will be the initial selected item of your dropdown with value equal to ''.

At Controller during POST mapLocationItemVal will have selected dropdown value.

The above shown code is best and simplest way to bind Dropdownlist in MVC.

Try this;

I assume you need to fill mapLocationItem.mapLocationItemType based on the selected value when you post the data.

@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes))

If you want to add CSS class you can do it as below.

@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes), new { @class = "your-class" })
Regan

Create a method in your controller

Public ActionResult Index()
{
   SampleDBContext db = new SampleDBContext();
   ViewBag.table_name = new SelectList(db.table_name, "DataValueField", "DataTextField");

   return View();
} 

View of the Controller

@Html.DropDownList("table_name", "select a item")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!