0

So I'm trying to pass my Razor page a list of objects, then have the user enter a value in for one field and pass it back to the controller to be updated in the database, however when it's passed back to the controller im just getting null.
Also is this actually a good way to handle this problem? -Note: never going to be large amounts of data
Models

public class SessionViewModel
{
    public List<Session> Sessions{ get; set; }
}

 public class GroupFitnessSession
{
    public string GroupFitnessSessionId { get; set; }
    public string GroupFitnessName { get; set; }
    public int SessionSize {get ; set;}
    public bool IsConfirmed {get ; set;
}

Controllers

// GET
public ActionResult ConfirmSessions()
{
    var model = new SessionViewModel();
    model.Sessions= unitOfWork.SessionsRepository.Get().ToList();
    return View(model);
}

// POST
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ConfirmSessions(SessionViewModel model)
{
    foreach (var item in model.GroupFitnessSessions)
    {
        item.IsConfirmed = true;
        unitOfWork.GroupFitnessSessionRepository.Update(item);
    }
    unitOfWork.Save();
    return View();
}

Razor

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <table class="table table-striped" style="margin-top: 25px;">
        @foreach (var item in Model.GroupFitnessSessions)
        {
            @Html.DisplayFor(modelItem => item.GroupFitnessName)
            @Html.EditorFor(modelitem => item.SessionSize)
        }
    </table>
    <input type="submit" value="Create" class="btn btn-block btn-default btn-width-1" />
}
Toxicable
  • 1,639
  • 2
  • 21
  • 29
  • 1
    You cannot use a `foreach` loop to generate form controls for a collection. It needs to be a `for` loop (or better use a custom `EditorTemplate` for typeof `Session` –  Jan 12 '16 at 01:49
  • This make sense, thanks for letting me know, I havn't used a EditorTemplate yet so I think ill just try using a for loop instead – Toxicable Jan 12 '16 at 01:53
  • Using an `EditorTemplate` is the better approach - refer [this answer](http://stackoverflow.com/questions/29486946/asp-net-mvc-parent-child-view-with-parent-view-updating-children/29487118#29487118) for an example –  Jan 12 '16 at 01:58

0 Answers0