簡體   English   中英

在ASP.Net MVC中回發后,在頁面重新加載時保持下拉菜單處於選中狀態

[英]Keep dropdown option selected on page reload after postback in ASP.Net MVC

如我所知,在MVC的DropdownListFor或DropdownList中,沒有回傳或編輯記錄后保持選項被選中的選項。

有人可以告訴我如何實現嗎?

這是我的示例代碼

@using (Html.BeginForm())
{
    @Html.DropDownList("menuitems",Model._menu,"Select Menu")
}

_menu是IEnumerable類型列表。 在瀏覽器上加載此頁面時,我希望通過索引號或其他方式選擇特定的DropDownList選項

列表模型-

public class MenuListModel
    {
        public long menuid { get; set; }
        public string menuname { get; set; }
    }

從數據庫獲取列表

public IEnumerable<MenuListModel> GetMenuItems()
        {
            List<MenuListModel> _MenuListModel = new List<MenuListModel>();
            var query = (from q in db.menus.Where(c => c.valid == true) select new{menuid=q.menuid,menuname=q.menuname});
            foreach (var row in query.ToList())
            {
                MenuListModel _menu = new MenuListModel();
                _menu.menuid = row.menuid;
                _menu.menuname = row.menuname;
                _MenuListModel.Add(_menu);
            }
            return _MenuListModel;
        }

控制者

IEnumerable<MenuListModel> _MenuListModel = ftwCommonMethods.GetMenuItems();
UserRightViewSearch _UserRightViewSearch = new UserRightViewSearch();
_UserRightViewSearch._menu = _MenuListModel;
return View(_UserRightViewSearch);

提前致謝。

以一個簡單的案例進行演示,在該案例中,用戶選擇了下拉列表並提交了整頁,並且控制器中的某些驗證失敗,或者您想發送至同一屏幕並保留所選值的其他原因。在這種情況下,請嘗試以下修改作為示例,那么您可以擴展您的要求。

查看代碼:

@Html.DropDownList("SelectedMenuItem", Model._menu.Select(menu => new SelectListItem { Text = menu.menuname, Value = menu.menuid.ToString() }), "--Select Menu--")

主視圖模型:

public class UserRightViewSearch
{
   public IEnumerable<MenuListModel> _menu { get; set; }
   public long SelectedMenuItem { get; set; } //Property to hold dropdown selection
}

控制器動作:

[HttpPost]
public ActionResult Index(UserRightViewSearch userRightView)
{
      //Here may be validation failed or for some other reason, return to same view
      userRightView._menu = GetMenuItems(); //Just for demo, but somehow you need to populate the default data to show as listbox items here, otherwise you see null reference exception or no items in list based on how you handle the case
      return View(userRightView);
}

希望這為您提供一些進一步探索的想法。

暫無
暫無

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

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