Search code examples
c#asp.net-mvcasp.net-mvc-4nulldropdownlistfor

DropDownListFor getting null value and appear ArgumentNullException


I attempting to do is passed a viewData from controller to view and display it in drop down list. I wish to add the selected Id pass into m.movie_type_id. But I keep on getting ArgumentNullException. Detailed information state that the Value cannot be null.

Below is how I was code and getting error exception.

<%=Html.DropDownListFor(m=> m.movie_type_id,new SelectList((IEnumerable)ViewData["MT"],"Id","Type")) %>

In Controller

public ActionResult AddMovie()
    {
        ViewData["MT"] = db.MovieType.ToList();
        return View();
    }

[HttpPost]
public ActionResult AddMovie()
    {
        return view();
    }

Current stage is just for testing purpose. Since the error occur during the data pass back to the controller, I wish to fix it before i proceed.

Where did I done wrong?


Solution

  • Please make sure that viewdata is filled by some collection and passed into your view like

    public ActionResult MyAction()
    {
      ViewData["MT"] =YourIEnumerableCollection() //Code to get the collection
      return view(model);
    }
    

    EDIT

    I think you are getting this in POST scenario, you need to pass the ViewData in POST too like

    [HttpPost]
    public ActionResult AddMovie()
    {
        ViewData["SQ"] = db.MovieType.ToList();
        return View();
    }