2

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 Answer 1

2

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)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.