I have a partial view that displays a viewmodel list containing 4 data columns. I want to have the user select 1 row and press a button to POST the Action. The view model looks like:
public class ViewModelSelection
{
public long SelectedItem { get; set; }
public List<ViewModelFromDB> Choices { get; set; }
}
The partial view looks like:
@model MyApp.ViewModels.ViewModelSelection
<h4>Title</h4>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<table>
<tr>
<th></th>
<th>Name</th>
<th>MeasureA</th>
<th>MeasureB</th>
</tr>
@foreach (var item in Model.Choices)
{
<tr>
<td>
@Html.RadioButton(item.id, Model.SelectedItem)
</td>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.measureA)
</td>
<td>
@Html.DisplayFor(modelItem => item.measureB)
</td>
</tr>
}
</table>
<input type="submit" value="Save" class="" />
}
I'd like the SelectedItem property of the viewmodel to be set to the id field of the selected row. Any suggestions much appreciated.
Your creating radio buttons with different names, so they are un grouped (i.e. you can select all of them) and have no relationship to your model. Change the radio button to
If you then post this to a controller method with parameter
int selectedItem
thenselectedItem
will contain the ID of the selectedChoice
. Alternatively you parameter could beViewModelSelection model
in which casemodel.SelectedItem
will contain the value.Side note: the
new { id = "" }
removes the inputsid
attribute to ensure you have valid html (no duplicateid
attributes)