MVC 中的下拉列表与实体中的 Where 子句

Dropdownlist in MVC with Where cluase in entities

我是 MVC 新手。我只想在 Account_Type = "D" 处填充下拉列表。 这是我的 Edit.cshtml

<div class="form-group">
        @Html.LabelFor(model => model.Account_Code, "Account_Code", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Account_Code", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Account_Code, "", new { @class = "text-danger" })
        </div>
    </div>

这是我的编辑控制器

public ActionResult Edit(int? id)
{
    ViewBag.Account_Code = new SelectList(db.Chart_Of_Account, "Account_Code", "Account_Desc", student.Account_Code);
}

使用 .Where() 子句过滤您的数据

public ActionResult Edit(int? id)
{
  var accountCodes = db.Chart_Of_Account.Where(a => a.Account_Type == "D");
  ViewBag.AccountCodeList = new SelectList(accountCodes , "Account_Code", "Account_Desc");
}

请注意,我更改了 ViewBag 属性 的名称并删除了 SelectList 构造函数的第三个参数(绑定到 属性 时会忽略它)

你的观点应该是

@Html.DropDownListFor(m => m.Account_Code, (SelectList)ViewBag.AccountCodeList)