【发布时间】:2019-05-29 21:33:23
【问题描述】:
我在 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);
模型有我需要的数据,但如何将其设置为正确的下拉列表值。我尝试使用简写 if 但它给了我一个错误
Invalid member initializer
我可以为 Selected Boolean 添加 if 条件吗?
【问题讨论】:
-
为什么要为模型使用索引器 -> 模型[i]
-
因为我是循环运行的
标签: c# asp.net-mvc razor model-view-controller html.dropdownlistfor