[英]populating dropdown from database while returning partial view in mvc using entity framework
我在mvc5中使用实体框架,我想通过从供应商模型中选择数据来填充用户View中数据库的下拉列表,并且还返回PartialView而不是简单View。 让我在这里分享我的代码。
这是供应商模型类。
[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; }
}
这是usersControler创建方法,我想在创建视图中填充下拉列表
// 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")
默认情况下,设置此初始字符串参数将使helper方法在ViewBag中搜索带有“ SuppliersList”标识符的SelectList。
编辑:由于您已请求使用HTML帮助器进行CSS更改,因此我们可以采用这种方式。
ViewBag.SuppliersList = new SelectList(db.Suppliers, "SupplierId", "Name");
然后在视图中:
@Html.DropDownList("SupplierId", ViewBag.SuppliersList as SelectList, new { @class = "someCssClass" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.