MVC DropDownListFor() Selected Item is not Selected / Required Validation not run

前端 未结 2 1201
囚心锁ツ
囚心锁ツ 2021-02-08 04:08

I am having trouble getting my DropDownList to set the selected item to the value from the model.

The field in the model is just a string for the Title of the users nam

2条回答
  •  隐瞒了意图╮
    2021-02-08 04:40

    So it turns out that the only reason it doesn't work is because my field name is Title, I changed it to Prefix and my exact code works. Way too much time spent finding that out...

    Here is working code.

    
        @{ var list = new List(new[] {
            new SelectListItem { 
                Selected = string.IsNullOrEmpty(Model.Prefix), 
                Text="",
                Value=""
            },
            new SelectListItem { 
                Selected = Model.Prefix.Equals("Mr"), 
                Text="Mr",
                Value="Mr"
            },
            new SelectListItem {
                Selected = Model.Prefix.Equals("Mrs"),
                Text="Mrs",
                Value="Mrs"
            },
            new SelectListItem {
                Selected = Model.Prefix.Equals("Miss"), 
                Text="Miss",
                Value="Miss"
            },
            new SelectListItem {
                Selected = Model.Prefix.Equals("Ms"), 
                Text="Ms",
                Value="Ms"
            }       
          });
        }
        @Html.DropDownListFor(m => m.Prefix, list)
    
    

提交回复
热议问题