【问题标题】:Set selected drop down value from database in razor view MVC在剃刀视图 MVC 中从数据库中设置选定的下拉值
【发布时间】: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


【解决方案1】:
@{
    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>

【讨论】:

  • 如果选择公寓怎么办,if条件太多。这不是一个好方法
  • 您的视图模型必须包含有关所选项目的信息。您不应该决定在视图中选择哪个项目,这必须在控制器中完成。
  • 你的模型是什么样子的?
猜你喜欢
  • 1970-01-01
  • 2015-11-30
  • 2017-10-06
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
相关资源
最近更新 更多