You can use? statement that works like this and uses the Selected property of selectlistitem
Console.WriteLine((2 == 2 ? "true" : "false"));
and then for example
private Entities en = new Entities(); public ActionResult Index(string selectedvalue) { List<SelectListItem> selectlist = en.tblUser.Select(x => new SelectListItem { Text = x.Name, Value = x.Id, Selected = ( x.Name == selectedvalue ? false : true) }) .ToList(); ViewBag.DropDown = selectlist; return View(); }
then in u view just put this
@Html.DropDownList("DropDownName", (List<SelectListItem>)ViewBag.DropDown))
Obviously, it is not recommended to use a viewbag, but instead use a model with a list property.
source share