0
我需要傳遞一個動態列表的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" />
}
什麼我需要做的,這樣的回發我能確定所選擇的單選按鈕?我必須缺少一些簡單的東西
用戶可以更改按鈕。我需要在回發 – WhiskerBiscuit
@WhiskerBiscuit是的,無論在發佈時的價值是什麼,它都會保存在模型中。 – ganders