好,幾個小時後,不成功嘗試所有的解決方案,還發現this article,我認爲它會救我的命...什麼都沒有。Html.DropDownList選定值不工作使用ViewBag
長話短說。
這裏是我的看法(所有組合)
@Html.DropDownList("yearDropDown",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
@Html.DropDownList("yearDropDownxxx",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
@Html.DropDownList("yearDropDown",(<SelectList>)ViewBag.yearDropDown)
@Html.DropDownList("yearDropDown")
這裏是我的控制器
public ActionResult(int year)
{
var years = new int[] { 2007, 2008, 2009, 2010, 2011, 2012 }
.Select(x => new SelectListItem {
Text = x.ToString(),
Value = x.ToString(),
Selected=x==year }).Distinct().ToList();
years.Insert(0, new SelectListItem { Value = null, Text = "ALL YEARS" });
ViewBag.yearDropDown = new SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault());
return View();
}
這是我提供的HTML。選擇無處可尋。
<select id="yearDropDown" name="yearDropDown"><option value="">ALL YEARS</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select>
不用說,但我會,我檢查了我的收藏和的SelectList實際上已經填充了選定的一年過去了控制器SelectedValue屬性。但是當我在視圖中渲染時,它會轉到第一個選項。
請,我需要爲DropDownList
的解決方案,而不是DropDownListFor
。我強調這一點,因爲我看到其他人在這裏要求相同的幫助,一羣人給他們指示,並幾乎訂購他們,使用DropDownListFor。有一個原因,我需要使用DropDownList。
SOLUTION: 看我自己的答案。 但是,以下是我所做的簡單更改。
控制器:
ViewBag.yearDropDown = years;
查看:
@Html.DropDownList("yearDropDown")
如果你看看我在視圖中的第二個例子,那正是我所做的。也沒有幫助。找到你的解決方案。看看我自己的答案。感謝您的時間和關注。 –
@Tony,解決方案是什麼? – Romias
我用解決方案編輯了我的問題。謝謝 –