簡體   English   中英

在剃刀視圖MVC中從數據庫設置選定的下拉值

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

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

我可以為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