heloo伙伴我已经使用Viewbag对象从mvc中的数据库填充了dropdownlist现在我想指定它的默认值,就像Select Supplier这里是我的Controler代码..
public ActionResult Create()
{
//IEnumerable<SelectListItem> SuppliersList = db.Suppliers.Select(c => new SelectListItem
//{
// Value = c.Name,
// Text = c.Name
//});
ViewBag.SupplierList = new SelectList(db.Suppliers, "Name", "Name");
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 });
}
return PartialView("_Create", frame);
}
和我的ViewCode
<div class="col-md-3">
@Html.LabelFor(model => model.Supplier)
@Html.DropDownList("Supplier", ViewBag.SupplierList as SelectList, new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.Supplier)
</div>
答案 0 :(得分:0)
如果您使用ViewBag和DropDownList
html辅助方法,则应在{{1}中设置所选项目的名称(您使用Name作为SelectLis t的值属性的正弦值)因为这是你在ViewBag.Supplier
辅助方法的第一个参数使用的值。
DropDownList
如果您想显示默认的“请选择”选项以及下拉选项,您可以使用此var suppliers = db.Suppliers.ToList();
ViewBag.SupplierList = new SelectList(suppliers , "Name", "Name");
// Here i am setting the 2 item in suppliers as the selected item.
// You can change it as needed
ViewBag.Supplier = suppliers[1].Name;
return PartialView("_Create");
方法的重载。
DropDownList
所以你的代码将是
public static MvcHtmlString DropDownList(
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes
)
另一种解决方案是不使用viewbag并使用强类型视图模型并使用@Html.DropDownList("Supplier", ViewBag.SupplierList as SelectList,
"Please select", new { @class = "form-control" })
辅助方法。 Here是如何做到的一个例子。
答案 1 :(得分:0)
只需实现optionLabel覆盖。
@Html.DropDownList("Supplier",
ViewBag.SupplierList as SelectList,
"Select Supplier",
new { @class = "form-control" })