Hi guys in new with asp mvc, so i having problem with the DropDown in edit view:
The ViewData item that has the key 'ProvinciaID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Provincia Model:
public class Provincia
{
public int ProvinciaID { get; set; }
[DisplayName("Provincia")]
[Required(ErrorMessage = "Provincia es requerida")]
public string ProvinciaNombre { get; set; }
}
Registro Model:
public class Registro
{
public int ID { get; set; }
....
[DisplayName("Provincia")]
[Required]
public int ProvinciaID { get; set; }
public List<Provincia> rProvincia { get; set; }
....
}
Controller
public ActionResult Edit(int id)
{
Registro registro = db.Registros.Find(id);
ViewBag.provincias = new SelectList(db.Provincias, "ProvinciaID", "ProvinciaNombre", registro.ProvinciaID);
return View(registro);
}
View
<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>
Any idea?
Thanks guys
The problem is that you are using this Edit view (the one you showed in your question) in some other controller action and this other controller action doesn’t set
ViewBag.provincias. You must always setViewBag.provinciasif you want to use this view. I suppose that this other controller action is the one you are POSTing to the form: