【问题标题】:Asp.Net MVC dropdownlist selected value dissappearsAsp.Net MVC 下拉列表选择的值消失
【发布时间】:2014-08-06 12:45:37
【问题描述】:

我有两个动作,我正在将数据传递给另一个。当我将数据第二个动作传递给第一个动作下拉列表的选定值时消失。我用谷歌搜索了很多小时,但我失败了。这是我的代码:

具有选择列表和操作代码的第一个操作。

第一个动作:

 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();
            }

第二个动作,我得到我的 SelectList 的 daire 值并将数据发送到第一个动作。

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

然后查看。

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

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

当用户点击按钮和页面刷新后,如何保持选中的 ListItem?

------------------------------编辑----- ------------------------------------------

如果有人需要,这里是解决方案--> 只需更改视图。

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

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4 tempdata


    【解决方案1】:

    如果TempData 有值,那么你可以传递int

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

    记住TempData是单次读取,读取值后会被删除,如果要持久化,请调用TempData.Keep("daire")

    【讨论】:

    • 感谢您的回答。我粘贴了您编写的代码,但仍然下拉的选定值 disseappers。
    • 我写的是控制器而不是动作。我正在尝试将数据操作传递给操作。
    【解决方案2】:

    问题在于 ModelState 持有下拉列表的传入值 在重定向到第一个控制器之前试试这个。Refere This

    ModelState.Remove("Page");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多