How to keep dropdownlist selected value after postback

后端 未结 6 1177
日久生厌
日久生厌 2020-12-19 13:03

In asp.net mvc3 how to keep dropdown list selected item after postback.

6条回答
  •  自闭症患者
    2020-12-19 13:40

    If you are building the drop down list data source in the controller Action Method you can send the selected value to it

    Controller:

     public ActionResult Index( int serviceid=0)
                {
    
    
                 // build the drop down list data source
                    List services = db.Service.ToList();
                    services.Insert(0, new Service() { ServiceID = 0, ServiceName = "All" });
                   // serviceid is the selected value you want to maintain
                    ViewBag.ServicesList = new SelectList(services, "ServiceID", "ServiceName",serviceid);
    
                   if (serviceid == 0)
                    {
                        //do something
                    }
                    else
                    {
                         // do another thing
    
                    }
                    return View();
               }
    

    View:

     //ServiceList is coming from ViewBag
    @Html.DropDownList("ServicesList", null, htmlAttributes: new { @class = "form-control" })
    

提交回复
热议问题