@Html.RadioButtonFor in mvc
本文关键字:mvc in RadioButtonFor @Html | 更新日期: 2023-09-27 17:54:00
在我的应用程序中,我的模型包含一个字段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;
}