簡體   English   中英

從下拉列表中檢索所有選定的Id值

[英]Retrieve all the selected Id's values from a drop down list

我有一個名為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

非常感謝您的幫助!

簡單地說,即使用是不可能DropDownListFor ......一個參數1 DropDownListFor是在你的模型,選擇列表中的數值屬性結合的領域。

如果要在發布時獲取對整個對象實體的引用,則需要根據從視圖返回的ID進行數據庫查找。

使用您的示例:

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);

然后在您的后控制器操作中:

//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對象,與從下拉列表中選擇的條目相對應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM