0

I have this in the controller:

public ActionResult Create(int id)
        {
 var enrollment = db.Events.FirstOrDefault(e => e.id == id);

            (...)

            var query = (from g in db.UserClass
                         join u in db.UserProfiles on g.UserId equals u.UserId
                         where g.ClassId == enrollment.ClassId
                         select new
                         {
                             UserClassId = g.UserClassId,
                             NameUser = u.Name
                         }).ToList();

            ViewBag.UserClassId = new SelectList(query, "UserClassId", "NameUser");

            return View("Create", attendance);
        }

And in the view:

@model List<Project.Models.Attendance>

(...)

            int y = 0;
            foreach (var x in Model)
            {
                <tr>
                    <td>@Html.DropDownListFor(a => a[y].UserClassId, (SelectList)ViewBag.UserClassId)</td>            
                </tr>
                    y++;
            }

    </table>

   (...)

When i click submit, this error appears:

There is no ViewData item of type ‘IEnumerable’ that has the key '[0].UserClassId'.

I already tried some ways that i found in other questions, like turn the ViewBag into ViewData and <td>@Html.DropDownListFor(a => a[j].UserClassId, (IEnumerable<SelectListItem>)ViewBag.UserClassId)</td> but nothing works. I'm stuck here, can someone help me? Thanks

Joao Costa
  • 21
  • 2
  • Because you return the view in the POST method, but do not repopulate the `ViewBag.UserClassId` property. But you usage make no sense. Note also that you cannot give the `ViewBag` property the same name as the property your binding to and you cannot use a `foreach` loop to generate form controls –  Aug 26 '16 at 22:40
  • 1
    Suggest you also refer the answers [here](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557) and [here](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o/34366306#34366306) and [here](http://stackoverflow.com/questions/37407811/mvc5-razor-html-dropdownlistfor-set-selected-when-value-is-in-array/37411482#37411482) –  Aug 26 '16 at 22:43

0 Answers0