简体   繁体   English

在mvc中的@ Html.RadioButtonFor

[英]@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. 在我的应用程序中,我的模型包含一个字段id ,在视图中我需要选择一个带有单选按钮的id并将选定的id发回给控制器。 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">
}

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 它需要包含所选User.Id的属性以及可供选择的用户集合

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM