1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmmm, okay, I hadn't thought of using that field. I am curious though - is this typically what developers do in an MVC environment? For some reason, this strikes me as something the attribute fields aren't intended for...
It maps more closely to how HTML form posts actually work; "on" (checked) items are submitted as post values. If your check boxes represent discrete values instead of an array of values, you can give them distinct names instead; they can then map to Boolean parameters in MVC.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.