假设我有一个像...这样的模型对象
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public DeliveryDetail
{
public string Description { get; set; }
public bool IsSelected { get; set; }
}
我将它传递给这样的 View ......
// Controller
public ActionResult Index()
{
MyModel myModel = Factory.CreateModelWithDeliveryDetails(x);
return View(myModel);
}
如何渲染/绑定(bind)一组单选按钮(在 View 中)?使用以下代码不会发回数据:
@foreach(var deliveryDetail in @Model.DeliveryDetails)
{
@deliveryDetail.Description
@Html.RadioButtonFor(x => deliveryDetail, false)
}
最佳答案
单选按钮列表中的选择是互斥的。您只能选择一个值。因此,将单选按钮列表绑定(bind)到 IEnumerable 类型的属性没有任何意义。您可能需要使 View 模型适应 View 的要求(在您的情况下, View 显示一个单选按钮列表,其中只能进行单个选择)。如果您使用了复选框列表,则绑定(bind)到 IEnumerable 属性将很有意义,因为您可以选中多个复选框。
所以让我们调整 View 模型以适应这种情况:
型号:
public class MyModel
{
public string SelectedDeliveryDetailId { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public class DeliveryDetail
{
public string Description { get; set; }
public int Id { get; set; }
}
Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel
{
DeliveryDetails = new[]
{
new DeliveryDetail { Description = "detail 1", Id = 1 },
new DeliveryDetail { Description = "detail 2", Id = 2 },
new DeliveryDetail { Description = "detail 3", Id = 3 },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Here you will get the id of the selected delivery detail
// in model.SelectedDeliveryDetailId
...
}
}
查看:
@model MyModel
@using (Html.BeginForm())
{
foreach (var deliveryDetail in Model.DeliveryDetails)
{
@deliveryDetail.Description
@Html.RadioButtonFor(x => x.SelectedDeliveryDetailId, deliveryDetail.Id)
}
<button type="submit">OK</button>
}
关于asp.net-mvc-3 - MVC 3、单选按钮和模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8680106/