简体   繁体   中英

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

As i know in DropdownListFor or DropdownList in MVC there is no option for keep option selected after postback or after Edit the record.

Can someone tell how to achieve this?

here is my sample code

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

here _menu is IEnumerable type list. While this page loads on browser, i want particular DropDownList Option selected by index number or some other way

List Model -

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

Getting List from Database

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

Controller

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

Thanks in advance.

Take a simple case to demo, where user selected dropdown and submit full page and some validation failed in controller or some other reason you want to send to same screen and retain selected value... In that case try with following modifications as an example and then you can extend to your requirement..

View Code:

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

Main View Model:

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

Controller Action:

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

Hope this provide you some idea to explore further..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM