heloo m using entity framework in mvc5 i want to populate dropdown list from database in users View by picking the data from suppliers model and m also returning a partialView instead of simple View. let me share my codes here.
this is Supplier Model Class.
[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; }
}
this is usersControler Create Method i want to populate dropdown in create View
// 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);
}
and here is _Create.cshtml partialView Code
<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>
You can use a different overload of Html.DropDownList more conveniently:
Change:
ViewData["SupplierList"] = new SelectList(db.Suppliers, "Name", "Name");
to:
ViewBag.SuppliersList = new SelectList(db.Suppliers, "Name", "Name");
in your action. Then in your view:
@Html.DropDownList("SuppliersList")
By default, setting this initial string parameter will cause the helper method to search the ViewBag for a SelectList with the "SuppliersList" identifier.
Edit: Since you've requested css changes using the Html helper, we can do it this way.
ViewBag.SuppliersList = new SelectList(db.Suppliers, "SupplierId", "Name");
Then in the view:
@Html.DropDownList("SupplierId", ViewBag.SuppliersList as SelectList, new { @class = "someCssClass" })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.