开发者

ASP MVC 3 DropDown list in Edit View

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

开发者_C百科
<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 set ViewBag.provincias if you want to use this view. I suppose that this other controller action is the one you are POSTing to the form:

[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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜