c# – @ html.RadioButtonFor in mvc

前端之家收集整理的这篇文章主要介绍了c# – @ html.RadioButtonFor in mvc前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,我的模型包含一个字段ID,在视图中我需要选择一个带有单选按钮的id并将选定的id发回给控制器.我怎样才能做到这一点?我的观点如下,
  1. @model IList<User>
  2.  
  3. @using (Html.BeginForm("SelectUser","Users"))
  4. {
  5. <ul>
  6. @for(int i=0;i<Model.Count(); ++i)
  7. {
  8. <li>
  9. <div>
  10. @Html.RadioButtonFor(model => Model[i].id,"true",new { @id = "id" })
  11. <label for="radio1">@Model[i].Name<span><span></span></span></label>
  12. </div>
  13. </li>
  14. }
  15. </ul>
  16.  
  17. <input type="submit" value="OK">
  18. }

解决方法

您需要更改模型以表示要编辑的内容.它需要包含所选User.Id的属性以及可供选择的用户集合
  1. public class SelectUserVM
  2. {
  3. public int SelectedUser { get; set; } // assumes User.Id is typeof int
  4. public IEnumerable<User> AllUsers { get; set; }
  5. }

视图

  1. @model yourAssembly.SelectUserVM
  2. @using(Html.BeginForm())
  3. {
  4. foreach(var user in Model.AllUsers)
  5. {
  6. @Html.RadioButtonFor(m => m.SelectedUser,user.ID,new { id = user.ID })
  7. <label for="@user.ID">@user.Name</label>
  8. }
  9. <input type="submit" .. />
  10. }

调节器

  1. public ActionResult SelectUser()
  2. {
  3. SelectUserVM model = new SelectUserVM();
  4. model.AllUsers = db.Users; // adjust to suit
  5. return View(model);
  6. }
  7.  
  8. [HttpPost]
  9. public ActionResult SelectUser(SelectUserVM model)
  10. {
  11. int selectedUser = model.SelectedUser;
  12. }

猜你在找的C#相关文章