简体   繁体   中英

RadioButtonFor model binding not working with Enum

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM