Jiju John
Jiju John

Reputation: 821

@Html.RadioButtonFor in mvc

In my application, my model contains a field id, and in the view I need to select an id with a radio button and post back the selected id to the controller. How can I do this? My view is as follows,

@model IList<User>

@using (Html.BeginForm("SelectUser", "Users"))
{
    <ul>
        @for(int i=0;i<Model.Count(); ++i)
        {
            <li>
                <div>
                    @Html.RadioButtonFor(model => Model[i].id, "true", new { @id = "id" }) 
                    <label for="radio1">@Model[i].Name<span><span></span></span></label>
                </div>
            </li>
        }
    </ul>

    <input type="submit" value="OK">
}

Upvotes: 6

Views: 15825

Answers (1)

user3559349
user3559349

Reputation:

You need to change you model to represent what you want to edit. It needs to include a property for the selected User.Id and a collection of users to select from

public class SelectUserVM
{
  public int SelectedUser { get; set; } // assumes User.Id is typeof int
  public IEnumerable<User> AllUsers { get; set; }
}

View

@model yourAssembly.SelectUserVM
@using(Html.BeginForm()) 
{
  foreach(var user in Model.AllUsers)
  {
    @Html.RadioButtonFor(m => m.SelectedUser, user.ID, new { id = user.ID })
    <label for="@user.ID">@user.Name</label>
  }
  <input type="submit" .. />
}

Controller

public ActionResult SelectUser()
{
  SelectUserVM model = new SelectUserVM();
  model.AllUsers = db.Users; // adjust to suit
  return View(model);
}

[HttpPost]
public ActionResult SelectUser(SelectUserVM model)
{
  int selectedUser = model.SelectedUser;
}

Upvotes: 12

Related Questions