嗨大家好用asp mvc,所以我在编辑视图中遇到DropDown问题:
The ViewData item that has the key 'ProvinciaID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
public class Provincia
{
public int ProvinciaID { get; set; }
[DisplayName("Provincia")]
[Required(ErrorMessage = "Provincia es requerida")]
public string ProvinciaNombre { get; set; }
}
public class Registro
{
public int ID { get; set; }
....
[DisplayName("Provincia")]
[Required]
public int ProvinciaID { get; set; }
public List<Provincia> rProvincia { get; set; }
....
}
public ActionResult Edit(int id)
{
Registro registro = db.Registros.Find(id);
ViewBag.provincias = new SelectList(db.Provincias, "ProvinciaID", "ProvinciaNombre", registro.ProvinciaID);
return View(registro);
}
<div class="editor-label">
@Html.LabelFor(model => model.ProvinciaID)
</div>
<div class="editor-field">
@Html.DropDownList("ProvinciaID", (IEnumerable<SelectListItem>)ViewData["provincias"]))
@Html.ValidationMessageFor(model => model.ProvinciaID)
</div>
有什么想法吗?
谢谢你们
答案 0 :(得分:2)
问题是您在其他控制器操作中使用此编辑视图(您在问题中显示的视图),而此其他控制器操作未设置ViewBag.provincias
。如果要使用此视图,则必须始终设置ViewBag.provincias
。我想这个其他的控制器动作就是你要发布到表单的动作:
[HttpPost]
public ActionResult Edit(Registro registro)
{
if (!ModelState.IsValid)
{
// I guess that here you are trying to redisplay the Edit view
// but you forgot to set ViewBag.provincias as you did in the
// GET Edit action and an exception is thrown because the Edit view
// always expects ViewBag.provincias to be set
// So set it before returning to the same view:
ViewBag.provincias = new SelectList(db.Provincias, "ProvinciaID", "ProvinciaNombre", registro.ProvinciaID);
return View(registro);
}
return RedirectToAction("Success");
}