MVC - Set selected value of SelectList

后端 未结 14 1169
后悔当初
后悔当初 2020-12-13 08:03

How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, \"I         


        
14条回答
  •  [愿得一人]
    2020-12-13 08:59

    I wanted the dropdown to select the matching value of the id in the action method. The trick is to set the Selected property when creating the SelectListItem Collection. It would not work any other way, perhaps I missed something but in end, it is more elegant in my option.

    You can write any method that returns a boolean to set the Selected value based on your requirements, in my case I used the existing Equal Method

    public ActionResult History(long id)
            {
                var app = new AppLogic();
                var historyVM = new ActivityHistoryViewModel();
    
                historyVM.ProcessHistory = app.GetActivity(id);
                historyVM.Process = app.GetProcess(id);
                var processlist = app.GetProcessList();
    
                historyVM.ProcessList = from process in processlist
                                        select new SelectListItem
                                        {
                                            Text = process.ProcessName,
                                            Value = process.ID.ToString(),
                                            Selected = long.Equals(process.ID, id)                                    
    
                                        };
    
                var listitems = new List();
    
                return View(historyVM);
            }
    

提交回复
热议问题