1

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 "

4
  • Are you using view model in your view? if yes then try new SelectList(Model.postes, "Id", "intitule_poste"),"choisir le poste") Commented Sep 10, 2014 at 13:20
  • i'm not using a ViewModel.... Commented Sep 10, 2014 at 13:27
  • On which line do you have the error and what is the exact message? Commented Sep 10, 2014 at 14:53
  • Please show us your entire view. If you don't have a ViewModel how can you set model => model.Id Commented Sep 10, 2014 at 14:55

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.