asp.netasp.net-mvc-4razorstrongly-typed-view

Strongly typed radiobutton list not posting back, shows empty when received from view


I'm trying to get a collection of radio buttons to postback. I'm able to display them on the form just fine, and when i submit i receive it on my controller but the list is empty, what am I doing wrong here?

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

VIEW

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

Updated with new Results

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

RESULTS

enter image description here


Solution

  • EDIT :

    Change your view model like:

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

    Change your foreach to for loop:

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

    You need to understand Model binding of List, Collection and Arrays, you can see details here