【发布时间】:2016-04-01 12:01:04
【问题描述】:
我很困惑如何使下拉列表显示所选值。
型号:
public class SampleModel
{
public string State { get; set; }
}
控制器:
public ActionResult EditInformation()
{
ViewBag.State = new SelectList(db.States, "StateName", "StateName");
string userEmail = User.Identity.GetUserName();
Sample model = new SampleModel();
model.State = "Melbourne";
return View(model);
}
查看:
@Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")
列表显示的状态很好,但它不会自动选择我分配的值(“墨尔本”)。我曾尝试使用 selectlist 构造函数来分配 selectedValue,但经过大量研究后,有人写道,如果您使用 Html.DropdownListFor(),则使用 selectlist 构造函数是多余的,因为您将使用分配给模型的值。
编辑:
这是我的 db.State 模型:
public class State
{
[Key]
public int StateId { get; set; }
public string StateName { get; set; }
}
再次澄清,我想使用 StateName 作为选择列表项的值和文本。
编辑: 我的完整动作方法:
public ActionResult EditInformation()
{
//var states = ndb.States.Select(s => new SelectListItem { Text = s.StateName, Value = s.StateName , Selected = s.StateName == "Jawa Timur" }).ToList();
ViewBag.State = new SelectList(ndb.States, "StateName", "StateName");
ViewBag.City = new SelectList(ndb.Cities, "CityName", "CityName");
string[] countries = { "Indonesia" };
ViewBag.Country = new SelectList(countries);
string userEmail = User.Identity.GetUserName();
try
{
UserInformation userInfo = ndb.UserInformations.Single(m => m.Email == userEmail);
UserAccountViewModel model = new UserAccountViewModel();
model.Address = userInfo.Address;
model.Email = userEmail;
model.FirstName = userInfo.FirstName;
model.LastName = userInfo.LastName;
model.Phone = userInfo.Phone;
model.PostalCode = userInfo.PostalCode;
Debug.Print(userInfo.State);
model.State = userInfo.State;
model.City = userInfo.City;
model.Country = userInfo.Country;
return View(model);
}catch { }
return View();
}
【问题讨论】:
-
你的
db.States是什么样的? -
你为什么要发布
SampleModel的模型,然后在你的ViewBag 中塞满db.States的东西?为States发布您的模型。你的db.States有ID吗? -
@BviLLe_Kid,实际上模型还有更多内容,我只是简化它以便你们更好地阅读,其余的只是简单的属性,它们按预期工作。我的 db.States 有一个 ID,但我更喜欢使用名称作为值。
标签: c# asp.net-mvc