404NotFound
404NotFound

Reputation: 635

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key

i'm trying to populate a dropdow list from a data base table,

i'm getting this error :

There is no ViewData item of type 'IEnumerable' that has the key 'QuartierId'.

Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code.

Détails de l'exception: System.InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'QuartierId'.

here my Model "QuartierSet" :

   public partial class Quartier
{
    public Quartier()
    {
        this.Publication = new HashSet<Publication>();
    }

    public int Quartier_Id { get; set; }
    public string Quartier_Libelle { get; set; }

    public virtual ICollection<Publication> Publication { get; set; }
    public virtual Ville Ville { get; set; }
}

My Controller Side:

 public ActionResult CreateOffreLocation(OffreLocation offreLocation)
    {
        try
        {

            ViewBag.QuartierId = new SelectList(db.QuartierSet, "Quartier_Id", "Quartier_Libelle");
            db.PublicationSet.Add(offreLocation);
            db.SaveChanges();
            return RedirectToAction("ListOffreLocation");

        }
        catch
        {
            return RedirectToAction("Error");
        }
    }

My view Side :

       @Html.DropDownList("QuartierId", String.Empty)

Upvotes: 1

Views: 2216

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

ViewBag is only available from the action in which you set it to the view of its action.

After setting in ViewBag you are redirecting to another action due to which the ViewBag is set to null again.

You need to add the following line in the ListOffreLocation action instead of CreateOffreLocation:

ViewBag.QuartierId = new SelectList(db.QuartierSet, "Quartier_Id", "Quartier_Libelle");

Upvotes: 1

chandresh patel
chandresh patel

Reputation: 309

@Html.DropDownList((SelectListItem)ViewBag.QuartierId, String.Empty)

Upvotes: 0

Related Questions