MVC5:将新值插入填充的 SelectList()?

MVC5: Insert new value into populated SelectList()?

在我的 MVC5 应用程序的主 INV_Assets 控制器中,我有一个 Edit() 方法,它通过 ViewBag 传递几个填充的 SelectLists() 以允许用户 select来自我数据库其他表中相关列表的所有可用实体 -- 注意,如果有比通过 ViewBag 传递它更好的做法,请随时指导我找到更好的方法。

        // GET: INV_Assets/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            INV_Assets iNV_Assets = await db.INV_Assets.FindAsync(id);
            if (iNV_Assets == null)
            {
                return HttpNotFound();
            }
            ViewBag.Location_Id = new SelectList(db.INV_Locations, "Id", "location_dept", iNV_Assets.Location_Id);
            ViewBag.Manufacturer_Id = new SelectList(db.INV_Manufacturers, "Id", "manufacturer_description", iNV_Assets.Manufacturer_Id);
            ViewBag.Model_Id = new SelectList(db.INV_Models, "Id", "model_description", iNV_Assets.Model_Id);
            ViewBag.Status_Id = new SelectList(db.INV_Statuses, "Id", "status_description", iNV_Assets.Status_Id);
            ViewBag.Type_Id = new SelectList(db.INV_Types, "Id", "type_description", iNV_Assets.Type_Id);
            ViewBag.Vendor_Id = new SelectList(db.INV_Vendors, "Id", "vendor_name", iNV_Assets.Vendor_Id);
            return View(iNV_Assets);
        }

我的列表目前填充得很好,但为了便于使用,我想在每个列表中插入一个 "Add New" 的值,单击时将打开相关 [= 的弹出窗口(部分视图?) 15=] 查看相关实体。例如,如果 Locations SelectList() 单击了 "Add New",我想打开位置的 Create 视图。

谁能举例说明如何做到这一点?

我一直在寻找如何在 SelectList() 中插入新值,但我似乎遇到的大多数情况都是使用放弃 SelectList() 的示例代替 Html.DropDownList(),虽然我不确定为什么?

SelectListclass继承IEnumerable<SelectListItem>,用于填充下拉列表。

给定 ViewModel object 具有以下 属性:

public SelectList Options
{
    get
        {
            var items = Enumerable.Range(0, 100).Select((value, index) => new { value, index });
            SelectList s = new SelectList(items, "index", "value");
            return s;
        }
 }

public int SelectedOption { get; set; }

view:

@Html.DropDownListFor(m => m.SelectedOption, Model.Options, "Add New", new { @class = "form-control" })

为了对弹出窗口执行您想要的操作,您可能需要一些 javascript 来处理它。

如果您不想要 DropDownListFor() 中的 "Add New",则需要在将其返回到视图之前手动将其添加到 collection。

希望对您有所帮助。