Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep dropdownlist selected value after postback

Tags:

asp.net-mvc

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

like image 586
user685254 Avatar asked Aug 08 '11 11:08

user685254


People also ask

How to keep selected value in DropDown list after refresh the page?

You can use localStorage to store selected value: $('#mov_type'). on('change', function() { // Save value in localstorage localStorage.

How to keep selected value in DropDown after submit in asp net?

You have (minimum) 2 options: 1) If you do not need any server side processing after clicking 'Cancel Button', you can use JavaScript and write history.go(-1) onclick of the button. That will take you to the previous page and drop-down-list will show the last selected value.

What is DropDownList AutoPostBack?

AutoPostBack of the ASP.Net DropDownList control provides the functionality to allow the server side post back event of the web page when user Select the DropDownlist Item from control while running programm.


2 Answers

Do something Like this :

[HttpPost]
    public ActionResult Create(FormCollection collection)
    {  if (TryUpdateModel(yourmodel))
            { //your logic 
              return RedirectToAction("Index");
            }
          int selectedvalue = Convert.ToInt32(collection["selectedValue"]);
           ViewData["dropdownlist"] = new SelectList(getAllEvents.ToList(), "EventID", "Name", selectedvalue);// your dropdownlist
            return View();
     }

And in the View:

 <%: Html.DropDownListFor(model => model.ProductID, (SelectList)ViewData["dropdownlist"])%>
like image 199
Mr A Avatar answered Oct 12 '22 13:10

Mr A


Even easier, you can include the name(s) of your dropdowns in your ActionResult input parameters. Your dropdowns should be in form tags. When the ActionResult is posted to, ASP.Net will iterate through querystrings, form values and cookies. As long as you include your dropdown names, the selected values will be preserved.

Here I have a form with 3 dropdowns that posts to an ActionResult. The dropdown names are (non-case sensitive): ReportName, Year, and Month.

    //MAKE SURE TO ACCEPT THE VALUES FOR REPORTNAME, YEAR, AND MONTH SO THAT THEY PERSIST IN THE DROPDOWNS EVEN AFTER POST!!!!
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ReportSelection(string reportName, string year, string month)
    {
        PopulateFilterDrowdowns();
        return View("NameOfMyView");
    }
like image 33
bjareczek Avatar answered Oct 12 '22 13:10

bjareczek