我需要传递一个动态的radiobuttonitems列表,并获取所选的单选按钮以及其他模型信息。
public class MyItem
{
public int Id { get; set; }
public String Name { get; set; }
public bool Selected { get; set; }
}
public class MyFormModel
{
public List<MyItem> RadioItems;
public String SomeQuestion;
public String SelectedButton { get; set; }
public String Answer { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var items = new List<MyItem>();
items.Add(new MyItem() { Id = 1, Name = "Male", Selected = true });
items.Add(new MyItem() { Id = 2, Name = "Female", Selected = false });
var m = new MyFormModel();
m.RadioItems = items;
m.SomeQuestion = "What's your favorite color?";
return View(m);
}
[HttpPost]
public ActionResult Index(MyFormModel model)
{
Console.WriteLine(model.Answer); //works
Console.WriteLine(model.SelectedButton); //does not work
return null;
}
查看
@model WebApplication1.Controllers.MyFormModel
@using (Html.BeginForm("Index", "Home", new {ReturnUrl = ViewBag.ReturnUrl}, FormMethod.Post, new {@class = "form-horizontal", role = "form"}))
{
foreach (var r in Model.RadioItems)
{
@Html.RadioButton("MyGroup",r.Id,r.Selected) @Html.Label(r.Name)<br/>
}
@Html.Label(Model.SomeQuestion) @Html.TextBoxFor(m=>m.Answer)
<input id="Submit1" type="submit" value="submit" />
}
我需要做什么才能在回发中确定所选的单选按钮?我一定错过了一些简单的事情
答案 0 :(得分:1)
您的模型必须与视图匹配,因此要么将视图更改为
@Html.RadioButton("SelectedButton",r.Id,r.Selected)
或添加
public string MyGroup {get;set;}
到你的模特。
答案 1 :(得分:0)
您可以在Html Helper中为模型指定“已选择”单选按钮。
@Html.RadioButtonFor(model => model.SelectedButton, "false")