1

i have binded the value from db to the dropdownlist. But when i try to submit in view, it shows :

The ViewData item that has the key 'Survey_Group' is of type 'System.String' but must be of type 'IEnumerable'.

Anyone can guide me? Thanks.

Model:

[MaxLength(100)]
[DisplayName("Owner Groups")]
public string Survey_Group { get; set; }

View:

@Html.LabelFor(model => model.Survey_Group, "Owner Groups")
@Html.DropDownListFor(model => model.Survey_Group, (SelectList)ViewBag.GroupList)

Controller:

public ActionResult SURV_Main_Create()
{
    ViewBag.CurrentPage = "create";
    var model = new SURV_Main_Model();
    ViewBag.GroupList = new SelectList(db.SURV_Group_Model, "Group_ID", "GroupName");
    return View(model);
}

// POST: /SURV_Main/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SURV_Main_Create(SURV_Main_Model surv_main_model)
{
    if (ModelState.IsValid)
    {
        var r = new Random();
        int randomno = r.Next(1, 1000000);
        surv_main_model.Survey_Key = "SURV" + DateTime.Now.ToString("yyyyMMddHHmmss") + randomno;
        surv_main_model.Survey_Creator = User.Identity.Name;
        db.SURV_Main_Model.Add(surv_main_model);
        db.SaveChanges();
        return RedirectToAction("SURV_Main_Edit", new { id = surv_main_model.Survey_ID });
    }
    return View(surv_main_model);
}
ramiramilu
  • 17,044
  • 6
  • 49
  • 66
Edward.K
  • 556
  • 3
  • 11
  • 33

1 Answers1

2

In your POST method, when the model is invalid, you return the view, but have not assigned a value to ViewBag.GroupList (which you use in the DropDownListFor() method) so its null, hence the exception.

In the POST method you need

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SURV_Main_Create(SURV_Main_Model surv_main_model)
{
  if (ModelState.IsValid)
  {
    ....
  }
  ViewBag.GroupList = new SelectList(db.SURV_Group_Model, "Group_ID", "GroupName"); // add this
  return View(surv_main_model);
}