简体   繁体   中英

Asp.Net MVC dropdownlist selected value dissappears

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" />
}

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")

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");

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