2016-01-22 95 views
1

我有一个单选按钮列表与IList视图模型在C#MVC 5.我的ViewModel值传递给控制器​​动作结果方法。单选按钮列表与C#MVC中的IList视图模型5

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

这里有一个选择的单选按钮,屏幕:

screenshot

这里是我的视图模型

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); 
} 

回答

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); 
+0

如果添加此方式,传递到字典的模型产品类型System.Collections.Generic.List的”。这是我的[HTTPGET]方法 变种模型= db.DeliveryPeriods 。选择(C => 新MainVM() { })ToList(); – Rob

+0

不需要,您需要初始化一个新的'MainVM'实例,然后将'Days'属性设置为一个集合。你没有提供足够的信息(我不知道'db.DeliveryPeriods'返回什么属性,如果你添加模型到问题和现有的GET方法,我可以更新答案。 –

+0

请告诉我怎么做现在改变[HttpGet]方法,现在就来了传入字典的模型项目类型为'System.Collections.Generic.List'1 [.ViewModels。MainVM]',但是这个字典需要一个'ViewModels.MainVM'类型的模型项。 – Rob