从下拉列表中检索所有选定的Id's值
本文关键字:Id 下拉列表 检索 | 更新日期: 2023-09-27 18:09:30
我有一个名为InvestigatorGroupData
的实体,其如下:
[DataContract]
public class InvestigatorGroupData
{
[DataMember]
public int InvestigatorGroupId { get; set; }
[DataMember]
public string InvestigatorGroupName { get; set; }
[DataMember]
public bool HasGameAssignment { get; set; }
}
我已经创建了以下视图模型:
public class InvestigatorGroupModel
{
public IEnumerable<InvestigatorGroupData> groupList {get;set;}
public int SelectedInvestigatorGroupId { get; set; }
}
并将其传递给视图,如下所示:
InvestigatorGroupModel groupModel = new InvestigatorGroupModel();
GameClient proxy = new GameClient();
groupModel.groupList = proxy.GetInvestigatorGroups(User.Identity.GetUserId());
proxy.Close();
return View("SelectGroup", groupModel);
我的视图的下拉列表看起来像这样:@Html.DropDownListFor(m => m.SelectedInvestigatorGroupId,new SelectList(Model.groupList, "InvestigatorGroupId", "InvestigatorGroupName"))
我希望用户能够选择InvestigatorGroupName
,并返回相关的InvestigatorGroupData
(而不仅仅是Selected Id)。到目前为止,只有SelectedInvestigatorGroupId
被返回/发布,groupList为null
使用您的示例:
InvestigatorGroupModel groupModel = new InvestigatorGroupModel();
GameClient proxy = new GameClient();
groupModel.groupList = proxy.GetInvestigatorGroups(User.Identity.GetUserId());
proxy.Close();
//Save the list of InvestigatorGroupData objects to be retrieved later
HttpContext.Current.Session["GroupList"] = groupModel.groupList;
return View("SelectGroup", groupModel);
然后在post controller action中:
//Grab the list of InvestigatorGroupData objects that was saved before
IEnumerable<InvestigatorGroupData> groupList = (IEnumerable<InvestigatorGroupData>)HttpContext.Current.Session["GroupList"];
int investigatorGroupId = groupModel.SelectedInvestigatorGroupId;
InvestigatorGroupData selectedGroup = groupList.Single(l => l.investigatorGroupId == investigatorGroupId);
selectedGroup
将是与下拉列表中所选条目对应的InvestigatorGroupData
对象。
简单地说,这是不可能使用DropDownListFor
…DropDownListFor
的参数1是模型中选择列表的value属性绑定到的字段。
如果您想在post上获得对整个对象实体的引用,那么您需要根据从视图返回的ID执行DB查找。