[英]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.