mvc在razor dropdownlistfor中设置默认值为bind to database

2eafrhcq  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(262)

问题是,如何在razor视图中设置与模型/数据库绑定的dropdownlistfor的默认值?
型号:

public class Cvm
{
    public TCl Cl { get; set; }
    public List<Purpose> ListPurpose { get; set; }

控制器:

public ActionResult Create()
{
    Cvm cvms = new Cvm();
    var purposes = db.Purposes.ToList();
    cvms.ListPurpose = purposes;
    return View(cvms);
}

看法

@{
  List<SelectListItem> listItems = new List<SelectListItem>();
  foreach (var item in Model.ListPurpose)
  {
    listItems.Add(new SelectListItem
    {
      Text = item.PurposeDesc
    });
  }
}
<div class="col-md-4">
  <div class="form-group">
    @Html.LabelFor(model => model.Clearance.Purpose, htmlAttributes: new { @class = "control-label" })
    <br>
    @Html.DropDownListFor(model => model.Clearance.Purpose, new SelectList(Model.ListPurpose, "Id", "PurposeDesc"), "Prime Purpose", new { @class = "form-control", Selected = true })
    @Html.ValidationMessageFor(model => model.Clearance.Purpose, "", new { @class = "text-danger" })
  </div>
</div>

这就是我现在用数据库中的数据填充dropdownlistfor的方式,当页面加载时,下拉列表被填充,并且下拉列表的值为“prime purpose”。
当我保存表单时,数据库中保存的内容在purpose列中为空,似乎忽略了加载的默认值

eqoofvh9

eqoofvh91#

我用电脑解决了我的问题

string defaultPupose = "LOCAL EMPLOYMENT";
Selected = item.PurposeDesc == defaultPupose ? true : false

完整代码为

@{
                    List<SelectListItem> listItems = new List<SelectListItem>();
                    string defaultPupose = "LOCAL EMPLOYMENT";
                    foreach (var item in Model.ListPurpose)
                    {
                        listItems.Add(new SelectListItem
                        {
                            Text = item.PurposeDesc,
                            Selected = item.PurposeDesc == defaultPupose ? true : false
                        });
                    }
                }

相关问题