Error in ASP.NET MVC SelectList. Value Cannot be null, parameter name: elements

This line causes me some problems in the MVC application that I am developing

<%= Html.DropDownListFor(model => model.TypeID, new SelectList((IEnumerable)ViewData["TaskingTypes"], "TypeID", "TypeName"))%> 

This causes an error in the header when the other two required fields in the form are not populated. When the fields are filled in, the form is submitted and written to db, without any problems. Does anyone have any ideas why validation is not matched and carried over into the view?

"TaskingTypes" is an object that has a relationship from 1 to many with the "Tasking" object. Key foriegn in "Tasking" - "TypeID"

Top 2 lines of the stack trace:

 [ArgumentNullException: Value cannot be null. [Parameter name: items] System.Web.Mvc.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, IEnumerable selectedValues) +262322 System.Web.Mvc.SelectList..ctor(IEnumerable items, String dataValueField, String dataTextField) +31 

This is the controller

 [AcceptVerbs(HttpVerbs.Get),Authorize] public ActionResult Create(){ Tasking tasking = new Tasking() { Created_On = DateTime.Now }; ViewData["TaskingTypes"] = tt.GetAllTaskingTypes().ToList(); return View(tasking); } [AcceptVerbs(HttpVerbs.Post),Authorize] public ActionResult Create(Tasking tasking) { if(TryUpdateModel(tasking)){ tasking.Created_On = DateTime.Now; tasking.Created_By = User.Identity.Name; taskingRepository.Add(tasking); taskingRepository.Save(); return RedirectToAction("Details", new { id = tasking.TaskingID }); } return View(tasking); } 

and this is a validation class

 public class Tasking_Validation { [Required(ErrorMessage = "Please select a tasking type")] public string TypeID { get; set; } [Required(ErrorMessage = "Tasking Title is Required")] [StringLength(255, ErrorMessage="Title cannot be longer than 255 characters")] public string Title { get; set; } [Required(ErrorMessage = "Location is Required")] [StringLength(255, ErrorMessage = "Location cannot be longer than 50 characters")] public string Location { get; set; } } 

Thanks so much for watching.

+4
source share
1 answer

You will need the following line:

 ViewData["TaskingTypes"] = tt.GetAllTaskingTypes().ToList(); 

also in the post method before you return the view if there is a validation error. This should fix your problem.

+4
source

All Articles