Search code examples
asp.netcontrollerformcollection

Getting values from the html to the controller


I'm trying to access the values a user introduces in a table from my controller.

This table is NOT part of the model, and the view source code is something like:

<table id="tableSeriales" summary="Seriales" class="servicesT" cellspacing="0" style="width: 100%">
    <tr>
        <td class="servHd">Seriales</td>
    </tr>
    <tr id="t0">
        <td class="servBodL">
            <input id="0" type="text" value="1234" onkeypress = "return handleKeyPress(event, this.id);"/>
            <input id="1" type="text" value="578" onkeypress = "return handleKeyPress(event, this.id);"/>
            .
            .
            .
        </td>
    </tr>
</table>

How can I get those values (1234, 578) from the controller?

Receiving a formcollection doesn't work since it does not get the table...

Thank you.


Solution

  • Using the FormCollection should work unless your table is not inside of a <form> tag


    On top of Lazarus's comment, you can try this, but you have to set the name attribute for each:

    <input id="seriales[0]" name="seriales[0]" type="text" value="1234" onkeypress="return handleKeyPress(event, this.id);"/>
    <input id="seriales[1]" name="seriales[1]" type="text" value="578" onkeypress="return handleKeyPress(event, this.id);"/>
    

    Now in your Action method you can make your method look like this:

    [HttpPost]
    public ActionResult MyMethod(IList<int> seriales)
    {
        // seriales.Count() == 2
        // seriales[0] == 1234
        // seriales[1] == 578
        return View();
    }
    

    and seriales will be wired up to those values.