簡體   English   中英

使用實體框架腳手架和 Razor 對下拉列表進行 MVC 過濾

[英]MVC filter on dropdownlist using entity framework scaffolding and Razor

這是一個非常基本的問題,我已經尋找了答案,但似乎沒有找到。 這是使用 VS2015 處理 Scaffolded MVC5 edit.cshtml。

我有 2 個表之間的 1:M 關系,子表有一個 @Html.DropDownList 作為父表的外鍵。 我需要過濾那個@Html.DropDownList。 這些是具體的:

一個 AssociationList 有許多 AgsweepParameters。

AssociationList 的主鍵是 AssociationListId,因此 AssociationListId 字段是 AgsweepParameter 表中的外鍵。

使用 EntityFramework 和 MVC5 Scaffolding,我使用 Entity Framework 作為模型創建了 crud 視圖/控制器。

該下拉列表的生成聲明如下所示:

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

問題:如何過濾該下拉列表,以便 AssociationList.AssociationType=="ACA"?

請注意,我在 AssociationList 表上的 Index.cshtml 上使用了類似的過濾器,如下所示:

            @foreach (var item in Model.Where(row=>row.AssociationType=="ACA")) {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { id=item.AssociationListId }) |
                        @Html.ActionLink("Delete", "Delete", new { id=item.AssociationListId })
                    </td>
                </tr>
            }

基本MVC在這里。 我必須執行以下操作:

了解控制器是定義過濾器而不是視圖的對象。 因此,我轉到公共 ActionResult Edit(int? id) 的控制器並更改

            ViewBag.AssociationListId = new SelectList(filteredAssociations, "AssociationListId", "Name", agsweepParameter.AssociationListId);

            IEnumerable<AssociationList> filteredAssociations = db.AssociationLists.Where(row => row.AssociationType == "ACA");
            ViewBag.AssociationListId = new SelectList(filteredAssociations, "AssociationListId", "Name", agsweepParameter.AssociationListId);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM