我正在尝试将视图包传递给DropDownList但是无效。
下拉列表错误
视图
<div class="form-group">
@Html.LabelFor(model => model.BanhoTosaId, "BanhoTosaId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("TransporteId", ViewBag.BanhoTosaId, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.BanhoTosaId, "", new { @class = "text-danger" })
</div>
</div>
控制器
// GET: AgendaBTs/Create
public ActionResult Create(int id, int pet)
{
ViewBag.BanhoTosaId = new SelectList(db.BanhoTosas, "BanhoTosaId", "Tipo");
ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "Nome", id);
ViewBag.PetId = new SelectList(db.Pets, "PetId", "PetNome", pet);
ViewBag.TransporteId = new SelectList(db.Transportes, "TransporteId", "Tipo");
if (ViewBag.BanhoTosaId != null && ViewBag.SelectedValue != null)
{
BanhoTosa BT = db.BanhoTosas.Find(ViewBag.BanhoTosaId);
Transporte TS = db.Transportes.Find(ViewBag.TransporteId);
decimal valorSoma = BT.Valor + TS.Valor;
ViewBag.Total = valorSoma;
}
else
{
ViewBag.Total = 0;
}
return View();
}
如果我这样下拉@Html.DropDownList(“TransporteId”,null,htm .... 在控制器中if,你抛出了else方法。
我该怎么做才能解决这个问题?
答案 0 :(得分:1)
你需要施放ViewBag.BanhoTosaId:
@Html.DropDownList("TransporteId", (List<SelectList>) ViewBag.BanhoTosaId, htmlAttributes: new { @class = "form-control" })
或强>
在Create
操作中,将其替换为:
ViewBag.TransporteId = new SelectList(db.Transportes, "TransporteId", "Tipo");
通过
ViewBag.TransporteId = db.Transportes;
然后在剃刀视图中添加:
@Html.DropDownList("TransporteId", new SelectList(ViewBag.TransporteId , "TransporteId", "Tipo"))
答案 1 :(得分:1)
你首先需要从你希望填充列表的数据中列出一个列表:
List<Category> CatList = db.Categories.ToList();
然后使用ViewBag:
ViewBag.CategoriesList = new SelectList(CatList, "CategoryID", "CategoryName");
之后你将会查看并写下:
<div class="form-group" style="margin-left:85px">
<div class="col-md-10">
@Html.DropDownListFor(model => model.CategoryID, ViewBag.CategoriesList as SelectList,
"Select Category", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })
</div>
</div>
这个例子来自我之前的工作
答案 2 :(得分:0)
替换
@Html.DropDownList("TransporteId", ViewBag.BanhoTosaId, htmlAttributes: new { @class = "form-control" })
带
@Html.DropDownList("TransporteId", (IEnumerable<SelectListItem>)ViewBag.BanhoTosaId,null, new { @class = "form-control" })