在我的应用程序中,我的模型包含一个字段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"> }
解决方法
您需要更改模型以表示要编辑的内容.它需要包含所选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; }