saidmohamed11
saidmohamed11

Reputation: 275

problems with getting data for dropdownlist

i have a dropdownlist getting data from data base

it contains 4 data :

my controller :

public ActionResult Index()
    {        
        ViewBag.Postes = _db.Postes.ToList();           
        return View();

    }

    [HttpPost]
    public ActionResult Index( Poste poste,string num_cin="R346399")
    {

        if (ModelState.IsValid)
        {
            if (poste.Id == 3)
            {
            return RedirectToAction("Inscription", "Candidat");
            }

        return View(poste);


          }

      }

my view

        @Html.DropDownListFor(model => model.Id,
        new SelectList(ViewBag.Postes, "Id", "intitule_poste"),"choisir le poste")

the problem that if i choose a value from dropdownlist that !=3 it's give me an error "that items must be not null "

Upvotes: 1

Views: 51

Answers (1)

user3559349
user3559349

Reputation:

You view includes @Html.DropDownListFor() which is generated based on the value of ViewBag.Postes. When you return the view (i.e. when poste.Id is not equal to 3) you must reassign the value of ViewBag.Postes

if (ModelState.IsValid)
{
  if (poste.Id == 3)
  {
    return RedirectToAction("Inscription", "Candidat");
  }
  ViewBag.Poste = _db.Postes.ToList(); // reassign collection for dropdown
  return View(poste);
}

Upvotes: 1

Related Questions