Pep*_*dez 5 html-select selectedvalue razor asp.net-mvc-3
好吧,经过几个小时阅读这里的东西,尝试所有的解决方案失败,也发现这篇文章,我认为这将拯救我的生命......没有.
长话短说.
这是我的观点(所有组合)
@Html.DropDownList("yearDropDown",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
@Html.DropDownList("yearDropDownxxx",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
@Html.DropDownList("yearDropDown",(<SelectList>)ViewBag.yearDropDown)
@Html.DropDownList("yearDropDown")
Run Code Online (Sandbox Code Playgroud)
这是我的控制器
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();
}
Run Code Online (Sandbox Code Playgroud)
这是我呈现的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>
Run Code Online (Sandbox Code Playgroud)
不用说了,但我会,我在我的Watch和SelectList中检查实际上已经将SelectedValue属性填充了所选年份传递给控制器.但是当我在视图中渲染时,它会转到第一个选项.
请,我需要解决方案DropDownList
,而不是DropDownListFor
.我正在强调这一点,因为我看到其他人在这里寻求相同的帮助,一群人给他们指示,并几乎订购它们,使用DropDownListFor.有一个原因我需要使用DropDownList.
解决方案:看看我自己的答案.但是,这是我所做的简单修改.
控制器:
ViewBag.yearDropDown = years;
Run Code Online (Sandbox Code Playgroud)
视图:
@Html.DropDownList("yearDropDown")
Run Code Online (Sandbox Code Playgroud)
小智 21
问题也可能是这个名字,请看这里.
在控制器中
ViewBag.PersonList= new SelectList(db.Person, "Id", "Name", p.PersonId);
Run Code Online (Sandbox Code Playgroud)
在视图中
@Html.DropDownList("PersonList",(SelectList)ViewBag.PersonList )
Run Code Online (Sandbox Code Playgroud)
这不起作用,你必须改变名称,所以它不一样.
@Html.DropDownList("PersonList123",(SelectList)ViewBag.PersonList )
Run Code Online (Sandbox Code Playgroud)
所以改变yearDropDown,它会为你工作.
最好的问候Christian Lyck.
将 ViewBag 属性的名称更改为与 DropDownList 的名称不匹配。使用ViewBag.yearDropDownDD
而不是ViewBag.yearDropDown
.
另外,您错误地创建了 SelectList。您需要传递选定的值而不是数组项:
ViewBag.yearDropDown = new
SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault().Value);
Run Code Online (Sandbox Code Playgroud)