在mvc中的@ Html.RadioButtonFor

时间:2015-06-08 04:49:29

标签: c# asp.net-mvc-4 razor

在我的应用程序中,我的模型包含一个字段id,在视图中我需要用一个单选按钮选择一个id并将所选的id回发给控制器。我怎样才能做到这一点?我的观点如下,

@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">
}

1 个答案:

答案 0 :(得分:9)

您需要更改模型以表示要编辑的内容。它需要包含所选User.Id的属性和要从中选择的用户集合

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

查看

@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" .. />
}

控制器

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;
}