![](/img/trans.png)
[英]Passing selected value of dropdownlist as property of Model asp.net mvc
[英]Asp.Net MVC dropdownlist selected value dissappears
我有兩個動作,我正在互相傳遞數據。 當我將數據傳遞給第一個動作的第二個動作時,下拉列表的選定值消失。 我用谷歌搜索了很多小時,但失敗了。 這是我的代碼:
具有選擇列表和操作代碼的第一個操作。
第一步:
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" />
}
如果TempData
有值,則可以傳遞int
:
if (TempData["daire"] != null)
{
int daire = Convert.ToInt32(TempData["daire"]);
ViewBag.daire = new SelectList(list, "Value", "Text", daire);
並記住TempData
是一次讀取,讀取值后將刪除它,如果要保留該值,請調用TempData.Keep("daire")
問題是ModelState保留了dropdownlist的傳入值在重定向到第一個控制器之前嘗試此操作。 引用此
ModelState.Remove("Page");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.