使用实体框架从数据库填充下拉列表,同时在 MVC 中返回部分视图
本文关键字:MVC 返回部 视图 框架 实体 数据库 下拉列表 填充 | 更新日期: 2023-09-27 17:56:13
heloo m 在 MVC5 中使用实体框架 我想通过从供应商模型中选取数据来填充用户视图中的数据库下拉列表,并且 m 还返回部分视图而不是简单视图。 让我在这里分享我的代码。
这是供应商模型类。
[MetadataType(typeof(MetadataForSupplier))]
public partial class Supplier
{
}
public class MetadataForSupplier
{
public int SupplierId { get; set; }
public string Name { get; set; }
public string ContactPerson { get; set; }
public string Address { get; set; }
}
这是用户控制创建方法我想在创建视图中填充下拉列表
// GET: /Frames/Create
public ActionResult Create()
{
return PartialView("_Create");
}
// POST: /Frames/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include="FrameId,Name,FrameCode,FrameFor,Brand,Material,Color,FrameType,FrameShape,Bridge,LensWidth,FrameWidth,TempleLength,LensHeight,FrameWeight,Quantity,PurchaseRate,SaleRate,Supplier,Discription,Status,CreatedOn")] Frame frame)
{
if (ModelState.IsValid)
{
db.Frames.Add(frame);
await db.SaveChangesAsync();
return Json(new { success = true });
}
//IEnumerable<SelectListItem> SuppliersList = db.Suppliers.Select(c => new SelectListItem
//{
// Value = c.Name,
// Text = c.Name
//});
ViewData["SupplierList"] = new SelectList(db.Suppliers, "Name", "Name");
return PartialView("_Create", frame);
}
这里是_Create.cshtml 部分视图代码
<div class="col-md-3">
@Html.LabelFor(model => model.Supplier)
@Html.DropDownList("Suppliers", (SelectList)ViewData["SupplierList"))
@Html.EditorFor(model => model.Supplier, new { htmlAttributes = new { @class = "form-control ", style = "width: 200px", @placeholder = "Supplier" } })
@Html.ValidationMessageFor(model => model.Supplier)
</div>
您可以更方便地使用不同的 Html.DropDownList 重载:
改变:
ViewData["SupplierList"] = new SelectList(db.Suppliers, "Name", "Name");
自:
ViewBag.SuppliersList = new SelectList(db.Suppliers, "Name", "Name");
在你的行动中。那么在您看来:
@Html.DropDownList("SuppliersList")
默认情况下,设置此初始字符串参数将导致帮助程序方法在 ViewBag 中搜索具有"供应商列表"标识符的选择列表。
编辑:由于您已使用 Html 帮助程序请求 css 更改,因此我们可以这样做。
ViewBag.SuppliersList = new SelectList(db.Suppliers, "SupplierId", "Name");
然后在视图中:
@Html.DropDownList("SupplierId", ViewBag.SuppliersList as SelectList, new { @class = "someCssClass" })