动态添加到已使用 ViewBag 填充的 @Html.DropDownList



我有一个@Html.DropDownList,我使用控制器中的 ViewBag 填充它。我正在寻找是否有可能让下拉列表从控制器加载值,但如果需要,还可以添加一个新值,然后在保存完整记录时保存它。

我的视图包含

 <div class="form-group">
        @Html.LabelFor(model => model.MaterialTypesID, "Material Type", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("MaterialTypesID", String.Empty)
            @Html.ValidationMessageFor(model => model.MaterialTypesID)
        </div>
    </div>

我的控制器 -

 private void PopulateMaterialTypeList(object selectMaterialType = null)
    {
        string voidInd = "Y";
        var materialType = db.MaterialTypes
            .Where(x => x.VoidInd == voidInd)
            .OrderBy(x => x.MaterialType1);
        ViewBag.MaterialTypesID = new SelectList(materialType, "MaterialTypesID", "MaterialType1", selectMaterialType);
    }

我认为使用MaterialTypesID.Items.Insert(0, new ListItem("Text","Value"));会起作用。还没有测试过,但我不知道在填充数据后会阻止你这样做。

最新更新