geekyhybrid
geekyhybrid

Reputation: 25

Passing HTML table information from MVC view to controller?

Is there a "best" (or preferred) way to pass information from an HTML table in an ASP.Net MVC view to a controller? I am working with MVC2, and if I stick with using the Context objects (mainly Request.Form[::variables::], I'm at a loss as to how to retrieve information presented in the view using the table/table cell structure. The table I am working with has a check box corresponding to each row of data, and I want to make the data from "checked" rows available to the controller. The following quick fixes come to mind:

1) Since the table in question has a check box, and HTML elements of type "input" have the "id" attribute, the data values could be stored in some kind of concatenated string in the "id" attribute for the check box.

2) Similar to the above misuse of the check box "id" attribute, the data values could be stored in the "text" attribute for a text (textbox) input element.

...but that all seems really klugey, even if it does work. I am relatively new to the field of web programming/development (although not new to programming), so if anyone can suggest alternate methods and/or technologies (I'm open to trying stuff via JavaScript, etc) I would appreciate it. I would appreciate even just links to relevant tutorials (or, related StackOverflow posts I may have missed). :-p

Upvotes: 1

Views: 4495

Answers (1)

Jacob
Jacob

Reputation: 78850

If you have a form like this:

<form action="." method="POST">
  <table>
    <tbody>
      <tr>
        <td>
          <input type="checkbox" name="checkedValues" value="1" />
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="checkedValues" value="2" />
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="checkedValues" value="3" />
        </td>
      </tr>
    </tbody>
  </table>
</form>

That will map to this parameter in your controller action when a post occurs, where the values of the checked boxes are stored in the checkedValues array:

public ActionResult MyAction(int[] checkedValues)
{
}

The values of the check boxes can be strings as well, if that's preferred.

Upvotes: 4

Related Questions