The viewbag isnt saving the `id` into the post action

Viewed 166
public ActionResult Attendance(FormModel form, int id)
    {
 ViewBag.studentname = new SelectList(db.Students, "StudentID", "Full_Name");
        ViewBag.studentID = new SelectList(db.Students, "StudentID", " StudentID");
        ViewBag.instructorID = new SelectList(db.Instructors, "InstructorID", "Name");
ViewBag.csID = id;
        var attendances = db.Attendances;
        return View(attendances.ToList());
    }

Here i save the id into a viewbag to use later:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Attendance([Bind(Include = "AttendanceID,csID,InstructorID,StudentID")] Attendance attendance)
    {
        try
        {
            if (ModelState.IsValid)
            {
                attendance.csID = ViewBag.csID;
                db.Attendances.Add(attendance);
                db.SaveChanges();
                //ViewBag.msg = "Instructor Added";
                return RedirectToAction("Attendance");

            }
            return View(attendance);
        }
        catch
        {
            return View(attendance);
        }
    }
}

} Over here i am trying the set the csid to the same value as the viewbag. When i debug it in the GET i get the int id but it isnt saving into the post when i debug it it says null in in both methods

1 Answers

How does one get from the first action method to the next? If the first is returning a view and that view has a form which posts to the second then there would be no reason to expect the ViewBag to contain values. Those are values sent to the view for the view to use, they are not retained server-side indefinitely.

If you want those values to post back to the server then you'd include them in the form being posted. For example, you might have a hidden input in your form:

<input type="hidden" name="csID" value="@ViewBag.csID" />

Then when you post that form the value would be included in the POST data.

It looks like the csID property is on your Attendance object, so it should be bound to that property automatically. However, that may depend on your model structure and form structure (which we don't see here). But you can tinker to account for that as needed.

Basically, if the property is part of your model and you want it to be posted from the page, included it in a form value on the page just like any other property of the model. (You may not even need to use ViewBag at all here, and I'm not sure why you are. You're sending Attendance models to the view and posting an Attendance model back to the controller, so it's not clear why you're making special considerations for some properties of that model.)

Related