C# Razor选择列表(DropDownList for)设置默认选定值

C# Razor选择列表(DropDownList for)设置默认选定值,c#,html,asp.net-mvc,razor,dropdownlistfor,C#,Html,Asp.net Mvc,Razor,Dropdownlistfor,我在视图模型中首先设置了一个选择列表,如下所示: public string selectedLocation { get; set; } public SelectList location = new SelectList(new[] { new SelectListItem { Text = "United Kingdom", Value = "GB" }, new SelectListItem {T

我在视图模型中首先设置了一个选择列表,如下所示:

  public string selectedLocation { get; set; }

        public SelectList location = new SelectList(new[]
        { 
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  {Text = "United States", Value = "US" , Selected = true },
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  { Text = "Australia", Value = "AU" },
            new SelectListItem  { Text = "China", Value = "CN" },
            new SelectListItem  { Text = "France", Value = "FR" },
            new SelectListItem  { Text = "Germany", Value = "DE" },
            new SelectListItem  { Text = "Italy", Value = "IT" },
            new SelectListItem  { Text = "Canada", Value = "CA" }
        }, "Value", "Text");
public ActionResult Index()
{ 
   var model = new myClassViewModel();
   model.selectedLocation = "IT"; // as rene stated
   return View(model);
}
如您所见,我已将US-select的默认值设置为true,因此应通过某种逻辑在下拉列表中选择此值

这就是我用HTML显示它的地方:

@Html.DropDownListFor(model => model.selectedLocation, Model.location, new { @class = "select2", @style = "width:95%;border-left:2px solid #eee" })
但无论我在viewmodel中设置了什么,下拉列表中的选定项始终是第一项


我做错了什么/

因此,问题的根源是,我必须在将模型传递到视图并按如下方式渲染之前设置model.selectedLocation值:

  public string selectedLocation { get; set; }

        public SelectList location = new SelectList(new[]
        { 
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  {Text = "United States", Value = "US" , Selected = true },
            new SelectListItem { Text = "United Kingdom", Value = "GB" },
            new SelectListItem  { Text = "Australia", Value = "AU" },
            new SelectListItem  { Text = "China", Value = "CN" },
            new SelectListItem  { Text = "France", Value = "FR" },
            new SelectListItem  { Text = "Germany", Value = "DE" },
            new SelectListItem  { Text = "Italy", Value = "IT" },
            new SelectListItem  { Text = "Canada", Value = "CA" }
        }, "Value", "Text");
public ActionResult Index()
{ 
   var model = new myClassViewModel();
   model.selectedLocation = "IT"; // as rene stated
   return View(model);
}

感谢@rene

模型中的值是多少。selectedLocation?@rene发布表单或呈现视图时?呈现视图时。我想这就是你的问题所在,对吧?很高兴你解决了…像这样很好。祝您有个美好的一天。