我有一个选择列表,我在我的视图模型中首先设置如下:
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");
正如您所看到的,我已经设置了美国的默认值 - 选择为true,因此应该通过某种逻辑在下拉列表中选择此值吗?
这是我用HTML显示的地方:
@Html.DropDownListFor(model => model.selectedLocation, Model.location, new { @class = "select2", @style = "width:95%;border-left:2px solid #eee" })
但是,无论我在viewmodel中设置什么,下拉列表中的所选项目始终是第一个...
我在这里做错了什么? :/
答案 0 :(得分:0)
所以问题的根源是我必须在将模型传递到视图中之前设置model.selectedLocation值并将其渲染为:
public ActionResult Index()
{
var model = new myClassViewModel();
model.selectedLocation = "IT"; // as rene stated
return View(model);
}
感谢@rene