0

I have two actions and i am passing data one to another. When i pass data second action to first action dropdown's selected value disappears. I googled many hours but i failed. Here is my codes:

First action which has selectlist and action codes.

First action:

 List<SelectListItem> list= new List<SelectListItem>
            {
            new SelectListItem {  Text = "--- Seçiniz----", Value = ""},
            new SelectListItem {  Text = "text1", Value = "11"},
            new SelectListItem { Text = "text2", Value = "12"},
            new SelectListItem {Text = "text3", Value = "13"},
            new SelectListItem {Text = "text4", Value = "14"},
            new SelectListItem { Text = "text5", Value = "15"}
            };

            if (TempData["daire"] != null)
            {

            int daire = Convert.ToInt32(TempData["daire"]);
            ViewBag.daire = new SelectList(list, "Value", "Text", TempData["daire"]);
            model= (folderBL.getAll().Where(k=>k.Id==daire)).ToList();
            }
           else
            {
            ViewBag.daire = new SelectList(list, "Value", "Text","");
            model= folderBL.getAll();
            }

Second action, I get the daire value for my SelectList and send data to first action.

  public ActionResult SecondAction(string daire)
        {
            TempData["daire"] = daire;
            return RedirectToAction("FirstAction");
        }

And View.

           @using (Html.BeginForm("SecondAction","MyDashboard",FormMethod.Post))
           {
            @Html.DropDownList("daire", (SelectList)ViewBag.daire, new { id = "mydrop" })

            <td><input type="submit" value="Send" />  
           }

How can i keep selected ListItem when user clicks button and after page refreshes?

-----------------------------------------EDİT----------------------------------------------

Here is the solution if someone needs--> Just change the View.

@using (Html.BeginForm("SecondAction", "MyDashboard", FormMethod.Post))
{
    @Html.DropDownList("daire")
    <input type="submit" value="Send" />
}
kojirosan
  • 497
  • 10
  • 25

2 Answers2

1

If TempData has value in it then you can pass the int:

if (TempData["daire"] != null)
        {

            int daire = Convert.ToInt32(TempData["daire"]);
            ViewBag.daire = new SelectList(list, "Value", "Text", daire);

and remember TempData is single read it will be removed after you read the value, if you want to persist it, call TempData.Keep("daire")

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

The problem was that ModelState was holding the dropdownlist's passed in value Try this before redirect to first controller.Refere This

ModelState.Remove("Page");
Community
  • 1
  • 1
Amol
  • 1,431
  • 2
  • 18
  • 32