0

I am trying to return table values of my view back to the controller to save on db but I keep getting null. I can post the values without problem and bind them to the view.

I cannot understand why, I am using a server side view model.

Is there any way to perform this?

View:

@model  IEnumerable<MultiEdit.Models.TableViewModel>

@using (Ajax.BeginForm("Save", "UUTs", new AjaxOptions
{
    HttpMethod = "Post",

}, new { id = "tableForm" }))
{
    @Html.AntiForgeryToken()
    <div class="row" style="padding-top:10px;">
        <div class="col-lg-12">
            <table class="table table-bordered table-striped ">
                <thead>
                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => model.IsChassis)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Justification)
                        </th>
                    </tr>
                </thead>
                <tbody id="tblMultiEdit">
                    @foreach(var item in Model)
                    {
                        <tr>
                            <td>
                                @Html.CheckBoxFor(modelItem => item.CheckIsChassis)
                            </td>
                            <td>
                                @Html.EditorFor(modelItem => item.Justification)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>
}

Controller:

public void Save(IEnumerable<TableViewModel> vm)
        {
            DoSomething();
        }
printthis
  • 141
  • 3
  • 11

2 Answers2

0

You need to iterate through your collection with a for loop and index qualifier. Something like the below. The syntax is not exact but you should be able to see what I mean.

@for(var index = 0; index <= Model.Count - 1; index++)
{
     <tr>
         <td>
             @Html.CheckBoxFor(modelItem => Model[index].CheckIsChassis)
         </td>
         <td>
             @Html.EditorFor(modelItem => Model[index].Justification)
         </td>
     </tr>
 }

This is required so the index can be used to create the unique id's of the Enumerable items and aids model binding

Hope that helps

Wheels73
  • 2,850
  • 1
  • 11
  • 20
0

I resolved it by using IList insead of IEnumerable.

View:

@model IList<MultiEdit.Models.TableViewModel>

@Html.CheckBoxFor(modelItem => modelItem[index].CheckIsChassis, new { @class = "form-control" })

Controller:

public void Save(IList<TableViewModel> vm)
    {
        var x = vm;
    }
printthis
  • 141
  • 3
  • 11