asp.net-mvc-3 - MVC 3、单选按钮和模型

标签 asp.net-mvc-3 c#-4.0 radio-button

假设我有一个像...这样的模型对象

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/

相关文章:

javascript - 使用 jQuery 插入带有标签的单选按钮

ruby-on-rails - Rails 应用程序单选按钮不更新 bool 字段

Asp.Net MVC3,返回成功 JsonResult

asp.net-mvc-3 - 如何在html5多文件上传中提供取消选项

xml - 加密整个 xml 文件 - C#

android - 使用 RadioButton/RadioGroup 行为创建 TextView(反之亦然)

database - 是否可以使用 foreach 条件在单元格中显示多个项目?

javascript - 如何防止浏览器后退按钮重新显示我的用户通知?

javascript - 在复选框选中更改事件中使用 Javascript 中的母版页时无法调用函数

c# - 为什么 Float 转换忽略小数点后的零?