在C#MVC 5中使用IList视图模型的单选按钮列表

时间:2016-01-22 04:10:47

标签: c# asp.net-mvc

我在C#MVC 5中有一个带有IList视图模型的单选按钮列表。我的ViewModel值被传递给控制器​​Action Result方法。

但是,该网页允许用户选择多个单选按钮。我需要如何为列表项选择单个按钮(一次一个)。

以下是所选单选按钮的屏幕:

screenshot

这是我的 ViewModel

public class DeliveryDateVM
{
    public int Id { get; set; }
    public bool SelectedItem { get; set; }
    public string DeliveryDay { get; set; }
    public string DeliveryType { get; set; }
}

这是我的查看

@model IList<ViewModels.DeliveryDateVM>

@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
  @for (var i = 0; i < Model.Count; i++)  {
    @Html.HiddenFor(x => x[i].Id)
    @{var uniqueID =  Model[i].Id;}

    <tr>
      <td>
        @{var uniqueID =  Model[i].Id;}
        @Html.RadioButtonFor(model => Model[i].SelectedItem, true, new { id = uniqueID })
      </td>
      <td>
        @Html.DisplayFor(x => x[i].DeliveryType)
        @Html.HiddenFor(x => x[i].DeliveryType)
      </td>
      <td>
        @Html.DisplayFor(x => x[i].DeliveryDay)
        @Html.HiddenFor(x => x[i].DeliveryDay)
      </td>
    </tr>
  }

  <button type="submit" class="btn btn-primary">Submit</button>
}

控制器值通过屏幕:

Controller Model Binder

这是我的 GET控制器

public ActionResult DeliveryDates()
{
  var model = db.DeliveryPeriods
               .Select(c =>
                    new DeliveryDateVM()
                {
                    Id = c.Id,
                    DeliveryDay = c.DeliveryDay,
                    DeliveryType = c.DeliveryType,

                }).ToList();

   return View(model);
}

1 个答案:

答案 0 :(得分:3)

单选按钮需要按名称分组,并为每个单选按钮指定不同的name属性。

将视图模型更改为

public class MainVM // rename as required
{
  public string SelectedDay { get; set; }
  public List<DeliveryDateVM> Days { get; set; }
}
public class DeliveryDateVM
{
    public int Id { get; set; }
    public string DeliveryDay { get; set; }
    public string DeliveryType { get; set; }
}

以便您查看

@model MainVM 
....
@for (var i = 0; i < Model.Days.Count; i++)
{
  @Html.RadioButtonFor(m => m.SelectedDay, Model.Days[i].DeliveryDay, new { id = "" })

  @Html.DisplayFor(m => m.Days[i].DeliveryType)
  @Html.HiddenFor(m => m.Days[i].DeliveryType)
  ....
}

现在生成name="SelectedDay"的所有单选按钮,并且当您回发到模型时,SelectedDay的值将是DeliveryDay的值(即“星期一”或“星期二“等等”

附注:您可能需要考虑将DeliveryDaySelectDay属性更改为DayOfWeek枚举,并为DeliveryType创建自己的枚举。

根据您的评论,修改后的get方法将是

MainVM model = new MainVM
{
  SelectedDay = "Monday", // set this if you want a default button selected
  Days = db.DeliveryPeriods.Select(c => new DeliveryDateVM()
  { 
    Id = c.Id, 
    DeliveryDay = c.DeliveryDay, 
    DeliveryType = c.DeliveryType,
  }).ToList()
};
return View(model);
相关问题