简体   繁体   English

在剃刀视图MVC中从数据库设置选定的下拉值

[英]Set selected drop down value from database in razor view MVC

I am explicitly creating a dropdownlist in razor mvc view. 我在razor mvc视图中明确创建了一个下拉列表。 I would like the default option to be one of the items, the value of that item should come from database 我希望默认选项是其中一个项目,该项目的值应来自数据库

View Code 查看代码

<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>

Controller Code 控制器代码

 cs.HomeType = serviceDetails.HomeType;
 sp.CustomerServices = cs;
 return View("EditCustomerServices", ProviderList);

Model has the data I need but how can I set it to correct Dropdown list value. 模型具有我需要的数据,但如何将其设置为更正下拉列表值。 I tried using short hand if but it gives me an error 我尝试使用短手,但它给了我一个错误

Invalid member initializer

Can I add if condition for Selected Boolean? 我可以为Selected Boolean添加if条件吗?

@{
    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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM