MVC razor partial view radio button selection for each row in model

3.2k Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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

@Html.RadioButtonFor(m => m.SelectedItem, item.id, new { id = "" })

If you then post this to a controller method with parameter int selectedItem then selectedItem will contain the ID of the selected Choice. Alternatively you parameter could be ViewModelSelection model in which case model.SelectedItem will contain the value.

Side note: the new { id = "" } removes the inputs id attribute to ensure you have valid html (no duplicate id attributes)