C# @mvc中的Html.radioButton
在我的应用程序中,我的模型包含一个字段C# @mvc中的Html.radioButton,c#,asp.net-mvc-4,razor,C#,Asp.net Mvc 4,Razor,在我的应用程序中,我的模型包含一个字段id,在视图中,我需要用单选按钮选择一个id,然后将所选id发回控制器。我该怎么做?我的看法是, @model IList<User> @using (Html.BeginForm("SelectUser", "Users")) { <ul> @for(int i=0;i<Model.Count(); ++i) { <li>
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">
}
@model-IList
@使用(Html.BeginForm(“SelectUser”、“Users”))
{
@对于(int i=0;i Model[i].id,“true”,新的{@id=“id”})
@型号[i].名称
}
}
您需要更改模型以表示要编辑的内容。它需要包括所选User.Id
的属性和要从中选择的用户集合
public class SelectUserVM
{
public int SelectedUser { get; set; } // assumes User.Id is typeof int
public IEnumerable<User> AllUsers { get; set; }
}
你的问题还不清楚你到底想做什么。再多解释一下就足够了。目前,您正在为每个
用户创建一个单独的单选按钮组(您可以选择一个或所有用户),并将User.id
属性绑定到true
(一个布尔值)。因为这些都没有任何意义,你需要解释一下你的目标是什么。最佳猜测您想发回所选用户的id
属性?@StephenMuecke是我想发回所选用户的iduser@JobinMathew然后,您需要在“返回”后的“选择”上相应地设置第二个参数,以获得所需的内容。编辑了我的答案检查我想应该是radiobutton for
not下拉列表可能是打字错误。Cheers和foreach缺少“@.”Supercol,如图所示不需要,但如果在
标签内,则需要
@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;
}