加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – @ html.RadioButtonFor in mvc

发布时间:2020-12-15 04:30:51 所属栏目:百科 来源:网络整理
导读:在我的应用程序中,我的模型包含一个字段ID,在视图中我需要选择一个带有单选按钮的id并将选定的id发回给控制器.我怎样才能做到这一点?我的观点如下, @model IListUser@using (Html.BeginForm("SelectUser","Users")){ ul @for(int i=0;iModel.Count(); ++i)
在我的应用程序中,我的模型包含一个字段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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读