MVC 3,单选按钮和模型

Dat*_*oon 3 radio-button c#-4.0 asp.net-mvc-3

鉴于我有一个像...的模型对象

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; }
}
Run Code Online (Sandbox Code Playgroud)

我把它传递给像这样的视图......

// Controller
public ActionResult Index()
{
  MyModel myModel = Factory.CreateModelWithDeliveryDetails(x);
  return View(myModel);
}
Run Code Online (Sandbox Code Playgroud)

如何渲染/绑定一组单选按钮(在视图中)?使用以下代码不会发回数据:

@foreach(var deliveryDetail in @Model.DeliveryDetails)
{
   @deliveryDetail.Description
   @Html.RadioButtonFor(x => deliveryDetail, false)
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 8

单选按钮列表中的选择是互斥的.您只能选择一个值.因此将单选按钮列表绑定到IEnumerable类型的属性没有任何意义.您可能需要使视图模型适应视图的要求(在您的情况下,显示单选按钮列表,其中只能进行单个选择).如果你使用了一个复选框列表,绑定到IEnumerable属性是有意义的,因为你可以检查多个复选框.

因此,让我们根据这种情况调整视图模型:

模型:

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; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

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
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

@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>
}
Run Code Online (Sandbox Code Playgroud)