MVC DropDownList selected value not working

人盡茶涼 提交于 2019-12-05 03:06:06

Set value of the Title property in the controller:

ViewBag.TitleList = new SelectList(new string[] { "Mr", "Miss", "Ms", "Mrs" });
viewModel.Title = "Miss"; // Miss will be selected by default

Another possible reason (and the correct one, based on the comments below) is that ViewData["Title"] is overridden by another value. Change name of the Title property to any other and everything should work.

Jose M.

When a value is not specified (i.e. "Id"), DropDownListFor sometimes does not behave properly. Try this:

public class FooModel
{
    public int Id { get; set; }
    public string Text { get; set; }
}

var temp = new FooModel[] 
{
    new FooModel {Id = 1, Text = "Mr"}, new FooModel {Id = 2, Text = "Miss"},
    new FooModel {Id = 3, Text = "Ms"}, new FooModel {Id = 4, Text = "Mrs"}
                       };
ViewBag.TitleList = new SelectList(temp, "Id", "Text", 2);

EDIT: other sololution

var temp = new []
{
    new SelectListItem {Value = "Mr", Text = "Mr"}, new SelectListItem {Value = "Miss", Text = "Miss"},
    new SelectListItem {Value = "Ms", Text = "Ms"}, new SelectListItem {Value = "Mrs", Text = "Mrs"}
};
ViewBag.TitleList = new SelectList(temp, "Value", "Text", "Miss");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!