强类型的radiobutton列表没有回发,从视图中收到时显示为空

时间:2014-07-02 14:59:22

标签: asp.net asp.net-mvc-4 razor strongly-typed-view

我正在尝试收集回传按钮的集合。我能够在表格上显示它们就好了,当我提交时,我会在我的控制器上收到它,但列表是空的,我在这里做错了什么?

查看-MODEL

public class ProfileViewModel
{
    public class FederalClassificationViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsSelected { get; set; }
    }

    public IList<FederalClassificationViewModel> federalClassificationsRadioViewModel { get; set; }
}

CONTROLLER

   //Retrieve all available radio buttons for tax information form
    var allTaxFederalClassList = _taxFederalRepo.GetAllTaxFederalClassesList();

    foreach (var federalClass in allTaxFederalClassList)
    {
        ProfileViewModel.FederalClassificationViewModel federalClassVM = new ProfileViewModel.FederalClassificationViewModel();

        federalClassVM.IsSelected = false;
        federalClassVM.Name       = federalClass.Name;
        federalClassVM.Id         = federalClass.id;

        model.federalClassificationsRadioViewModel.Add(federalClassVM);
    }

查看

@foreach(var radio in Model.federalClassificationsRadioViewModel)
{
    @Html.RadioButtonFor(p=>p.federalClassificationsRadioViewModel, radio) @radio.Name
}

更新了新结果

@for(int i=0; i<Model.federalClassificationsRadioViewModel.Count; i++)
{
   @Html.RadioButtonFor(p=>p.federalClassificationsRadioViewModel[i].IsSelected, Model.federalClassificationsRadioViewModel[i].Id) @Model.federalClassificationsRadioViewModel[i].Name
}

结果

enter image description here

1 个答案:

答案 0 :(得分:1)

编辑:

更改您的视图模型,如:

public class ProfileViewModel
{

    public class FederalClassificationViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsSelected { get; set; }
    }

    public int SelectedClass {get;set;}
    public IList<FederalClassificationViewModel> federalClassificationsRadioViewModel { get; set; }
}

将您的foreach更改为for循环:

    @for(int i=0; i<Model.federalClassificationsRadioViewModel.Count; i++)
    {
        @Html.RadioButtonFor(p=>p.
SelectedClass,Model.federalClassificationsRadioViewModel[i].Id) @Model.federalClassificationsRadioViewModel[i].Name
    }

您需要了解ListCollectionArrays的模型绑定,您可以看到details here