[英]shows a specific value in MVC DropDownList that matchs a viewbag value
我在MVC C#应用程序中确实有一个Html.DropDownListFor,用户可以选择特定的值(年:2017、2018、2019、2020),如下所示
<div class="col-md-3">
@Html.LabelFor(model => model.correlativo2, htmlAttributes: new { @class = "control-label" })
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Seleccione</span>
@Html.DropDownListFor(model => model.correlativo2, new List<SelectListItem> { new SelectListItem { Text = "2017", Value = "2017" }, new SelectListItem { Text = "2018", Value = "2018" }, new SelectListItem { Text = "2019", Value = "2019" }, new SelectListItem { Text = "2020", Value = "2020" }, new SelectListItem { Text = "2021", Value = "2021" } }, "", new { @class = "form-control", @id = "idEjercicio", @title = "especifique ejercicio de licitación", @Value = ViewBag.ejercicio })
</div>
@Html.ValidationMessageFor(model => model.correlativo2, "", new { @class = "text-danger" })
</div>
因为值是常数(年)并且不会改变(两者都不依赖于任何其他值),所以我不查询数据库以指定下拉列表的值,但是@Value = ViewBag.ejercicio
具有特定值(例如:2017、2018、2019、2020),因此我希望下拉列表显示与该值匹配的年份,但是即使Viewbag具有值也不会显示任何内容。
这是ViewBag: ViewBag.ejercicio = Convert.ToString(datos.correlativo2);
请你帮助我好吗
您可以尝试设置Selected
属性并改用DropDownList
:
<div class="col-md-3">
@Html.LabelFor(model => model.correlativo2, htmlAttributes: new { @class = "control-label" })
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Seleccione</span>
@{
var years = new List<SelectListItem> { new SelectListItem { Text = "2017", Value = "2017" }, new SelectListItem { Text = "2018", Value = "2018" }, new SelectListItem { Text = "2019", Value = "2019" }, new SelectListItem { Text = "2020", Value = "2020" }, new SelectListItem { Text = "2021", Value = "2021" } };
foreach (var year in years)
{
year.Selected = year.Value == ViewBag.ejercicio;
}
}
@Html.DropDownList("correlativo2", years, "", new { @class = "form-control", @id = "idEjercicio", @title = "especifique ejercicio de licitación" })
</div>
@Html.ValidationMessageFor(model => model.correlativo2, "", new { @class = "text-danger" })
</div>
但是确实最好像@AndrewReyes建议的那样设置模型属性的值。 然后Razor将自动为您设置选定的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.