[英]How can I set selected equals to True in a DropDownList in ASP.NET
I have this code:我有这个代码:
@Html.DropDownList("ddlTiposUsuarios", Model.tiposUsuarios.Select(item => new SelectListItem
{
Value = item.Id_Tipo_Usuario.ToString(),
Text = item.Nombre_Tipo_Usuario.ToString(),
Selected = "select" == item.Id_Tipo_Usuario.ToString()
}), new { @class = "form-select", aria_label = "Default select eaxmple" })
I retrieve a list of four elements from SQL Server and I want to set an option html element which "selected" attribute equals true, depending query from Controller.我从 SQL 服务器检索四个元素的列表,我想设置一个选项 html 元素,其中“选定”属性等于 true,具体取决于来自 Controller 的查询。 Any tips?
有小费吗?
Instead of creating the SelectList
on your View
, create the list in your Controller
and set it to a ViewBag
and see how easy it becomes after that:与其在
View
上创建SelectList
,不如在Controller
中创建列表并将其设置为ViewBag
,然后看看它变得多么容易:
In your Controller
, do this:在您的
Controller
中,执行以下操作:
ViewBag.myddlItems = tiposUsuarios.Select(item => new SelectListItem
{
Value = item.Id_Tipo_Usuario.ToString(),
Text = item.Nombre_Tipo_Usuario.ToString()
});
and then in your View, you can construct your DropDownList
using the ViewBag
:然后在您的视图中,您可以使用
ViewBag
构建DropDownList
:
<select id="ddlTiposUsuarios" class="form-select" aria_label = "Default select eaxmple">
@foreach (SelectListItem option in ViewBag.myddlItems)
{
<option value="@option.Value" @(option.Value == "select" ? "selected='selected'" : "")>@option.Text</option>
}
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.