我在View
@Html.DropDownList("GenderAllowed", (SelectList)ViewBag.LocGenederAllowedList, new { @class = "form-control" })
我正在通过ViewBag
发送下拉列表,并通过模型发送需要在下拉列表中选择的值。
但是未选择下拉列表中的值。
我的控制器
[HttpGet]
public ActionResult EditVendorLocation(int VendorLocationID)
{
VendorLocationHandler obj = new VendorLocationHandler();
LocationGrid objLoc = new LocationGrid();
FillGenederAllowed(objLoc);
objLoc = obj.GetVendorLocationForAdmin(VendorLocationID);
return View(objLoc);
}
Viewbag的功能
public void FillGenederAllowed(LocationGrid V)
{
Dictionary<int, string> LocGenederAllowed = EnumHelper.GetGenderStates();
SelectList LocGenederAllowedList = new SelectList(LocGenederAllowed, "key", "value");
ViewBag.LocGenederAllowedList = LocGenederAllowedList;
}
答案 0 :(得分:1)
您传递给DropDownList的SelectListItems
具有属性Selected
。在ViewModel中,对于最初应选择的项目,将其设置为true。
答案 1 :(得分:0)
您可以在控制器操作中执行此操作,如下所示。希望它有所帮助。
ViewBag.LocGenederAllowedList = new SelectList(items, "Id", "Name", selectedValue);
点网小提琴链接:https://dotnetfiddle.net/PFlqei
答案 2 :(得分:0)
看看this课程。
您需要做的就是创建它们的实例,并为最初要选择的项目将Selected
属性设置为true:
public ActionResult YourActionMethod(...)
{
var selectItems = Repository.SomeDomainModelObjectCollection
.Select(x => new SelectListItem {
Text = x.SomeProperty,
Value = x.SomeOtherProperty,
Selected = ShoudBeSelected(x)
});
ViewBag.SelectListItems = selectItems;
// more code
var model = ...; // create your model
return View(model);
}
您需要Html.DropDownListFor(...)
的重叠才能使用this。
答案 3 :(得分:0)
你需要在控制器中使用它
ViewBag.LocGenederAllowedList =
new SelectList(db.SomeValues, "Value", "Text",selectedValue);
在你看来
@Html.DropDownList("GenderAllowed",
(SelectList)ViewBag.LocGenederAllowedList, new { @class = "form-control" })