Search code examples
asp.net-mvcrazorengine

Pass Table Value from View to Controller MVC


Can I pass table td values to controller?

View strongly typed:

@using (Html.BeginForm("PostClick", "Vendor", FormMethod.Post)) {
<table class="tblData">
  <tr>
    <th>
      @Html.DisplayNameFor(model => model.First().SubmittedDate)
    </th>
    <th>
      @Html.DisplayNameFor(model => model.First().StartDate)
    </th>
  </tr>

  <tr>
    <td>
      @Html.DisplayFor(modelItem => item.SubmittedDate)
    </td>
    <td>
      @Html.DisplayFor(modelItem => item.StartDate)
    </td>
   </tr>
 </table>
 <input type="submit" value="submit" />
    }

Contoller code:

public void PostClick(FormCollection collection)
{
   /*Some Code */
} 

How to pass table value from view to controller?

Have used JasonData & Ajax call and able to send the table data to controller.

Want to know any other method can be done because FormCollection data not able to find table values


Solution

  • Your need to generate controls that post back (input, textarea or select) and generate those controls in a for loop (or use a custom EditorTemplate for type Vendor)

    View

    @model List<Vendor>
    @using (Html.BeginForm())
    {
      <table class="tblData">
        <thead>
          ....
        </thead>
        <tbody>
          for(int i = 0; i < Model.Count; i++)
          {
            <tr>
              <td>@Html.TextBoxFor(m => m[i].SubmittedDate)</td>
              <td>@Html.TextBoxFor(m => m[i].StartDate)</td>
            </tr>
          }
        </tbody>
      </table>
      <input type="submit" value="submit" />
    }
    

    Post method

    public void PostClick(List<Vendor> model)
    {
      /*Some Code */
    }