0

I am trying to implement a form that contains a grid-like structure of radio buttons. There are four radio buttons, one of which can be selected. In the model I have an Enum to hold the four options and the model has reference to this.

The Enum:

public enum HubType
{
    Hub5 = 0,
    Hub3 = 1,
    Router = 2,
    Others = 3,
}

The Model:

public class Customer
{
    public string ReferenceId { get; set; }
    public CustomerType Type { get; set; }

    public int ChangesMade = 0;
    public DateTime MigrationDate { get; set; }
    public bool MigrationDateChanged = false;
    public List<SiteDetails> Sites = new List<SiteDetails>()
    {
        new SiteDetails { SiteAddress = "test address 1", Hub = HubType.Hub3 },
        new SiteDetails { SiteAddress = "test address 2", Hub = HubType.Hub5},
        new SiteDetails { SiteAddress = "test address 3", Hub = HubType.Router},
        new SiteDetails { SiteAddress = "test address 4", Hub = HubType.Hub5}
    };
}

SiteDetails.cs

public class SiteDetails
{
    public String SiteAddress { get; set; }
    public HubType Hub = HubType.Hub5;
}

Finally the partial view SiteDetails.cshtml

@model MyApp.Models.Customer
@using MyApp.Models.Enums
@{
    var hubTypes = Enum.GetValues(typeof(HubType));
}

@using (Html.BeginForm("SiteDetails", "MyApp", FormMethod.Post))
{
    @for(int site = 0; site < Model.Sites.Count; site++)
    {
        @Model.Sites[site].SiteAddress
        @for (int hub = 0; hub < hubTypes.Length; hub++)
        {
            @Html.RadioButtonFor(m => m.Sites[site].Hub, hubTypes.GetValue(hub))
        }
        <input type="submit" class="button right" value="Save 
    }
}

When I submit the page, I expect the model property to be populated with the selected value, which is not happening now. Please help me to explore where I am doing wrong and if there is any better approach to do this. Thanks in advance!

ATT
  • 337
  • 3
  • 10
  • You cannot use a `foreach` loop to generate form controls for collections. –  Mar 09 '16 at 09:10
  • Thanks for the answer. I have replaced the foreach loops with conventional for loops, but the problem still persists. I have edited the code for view. – ATT Mar 09 '16 at 09:38
  • I have reopened the question, but you have multiple other errors as well - will add answer shortly. –  Mar 09 '16 at 10:06

1 Answers1

0

List<SiteDetails> Sites and HubType Hub are fields, not properties so the DefaultModelBinder cannot set the value. You need to make them properties

public class Customer
{
    ....
    public List<SiteDetails> Sites { get; set; }
}
public class SiteDetails
{
    ....
    public HubType Hub = { get; set; }
}

and then assign those values in the controller (or in a parameter-less constructor). Note also that int ChangesMade and bool MigrationDateChanged are also fields, but you do not appear to be using those in the view.