I'm struggling to figure out the correct way to do something in MVC which wouldn't be difficult in WebForms, and I'm hoping someone will be able to point me in the right direction.
Basically, I am displaying a table of data and the user should be able to select zero or more rows. When they press submit I want my controller to know which rows have been selected, as that will affect other data on the screen.
My View looks like this:
<form action="/Summary/Index" method="post">
<table>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<% foreach (Person p in Model)
{ %>
<tr>
<td>
<input type="checkbox" name="" /> <!-- HOW SHOULD THIS BE RENDERED? -->
</td>
<td><%= p.Name %></td>
<td><%= p.Age %></td>
</tr>
<% } %>
</tbody>
</table>
<input type="submit" value="Update" />
</form>
So when the submit button is clicked, the form will post to the current url. Note that the model 'Person' is just a ViewModel so I can add any necessary UI related properties if required. Should I add a 'Selected' property to Person and have my controller take a list/array of Person and check the selected property of each?
Please note that I need a solution that will work without JavaScript, and I don't want my controller to be concerned with how the values of the checkboxes are retrieved - I'm happy to write a custom ModelBinder if needed.
Can anyone give me an idea how to do this please?
Thanks very much, Simon.
If there is a person ID or some other unique identifier then structure it thus:
<% foreach (Person p in Model)
{ %>
<tr>
<td>
<input type="checkbox" name="selectedNames" value="<%= p.ID %>" /> <!-- HOW SHOULD THIS BE RENDERED? -->
</td>
<td><%= p.Name %></td>
<td><%= p.Age %></td>
</tr>
<% } %>
You then be able to add the return to your controller method "string[] selectedNames", i.e.
public void ProcessReturn(string[] selectedNames)
{
foreach (string nameID in selectedNames)
{
ProcessNameByID(nameID);
}
}
The array will include the 'value' of each checkbox that was checked, and only those that were checked!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With