我正在razor mvc视图中显式创建一个下拉列表。我希望默认选项是其中一项,该项目的值应来自数据库
查看代码
<div class="form-group">
@Html.LabelFor(model => model[i].Customer.HomeType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
@Html.DropDownListFor(model => model[i].Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House",@(Model[i].CustomerServices.HomeType == "House" ? Selected = true : false) },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { @class = "form-control" })
}
</div>
</div>
控制器代码
cs.HomeType = serviceDetails.HomeType;
sp.CustomerServices = cs;
return View("EditCustomerServices", ProviderList);
模型具有我需要的数据,但是如何将其设置为正确的下拉列表值。我尝试使用短手如果,但给我一个错误
Invalid member initializer
是否可以为条件添加选定布尔值?
答案 0 :(得分:0)
@{
var selected = Model.CustomerServices.HomeType == "House";
}
<div class="form-group">
@Html.LabelFor(model => model.Customer.HomeType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
@Html.DropDownListFor(model => model.Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House", Selected = selected },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { @class = "form-control" })
}
</div>
</div>