Setting a default selected value in DropDownList in MVC3

本小妞迷上赌 提交于 2019-12-01 03:25:26

There's an overload for the SelectList constructor that takes 4 arguments. The last of which is the default selected object. E.g:

ViewBag.Vessels = new SelectList(vs, "InstId", "InstName", selectedValue);

Where selectedValue is an object of whatever type is in your list.

I need to set first item in the ViewBag List as a default selected value, instead of "- Select one -" text.

Then you need to select the first item in your list (vs) and get it's id and use it as the selecedValue in the SelectList:

ViewBag.Vessels = new SelectList(vs, "InstId", "InstName", 
    vs.FirstOrDefault().InstId);

You can also create an Helper class for Dropdownlist It will have a method to set the text as by default text for every dropdownlist in you solution

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