ASP.NET MVC Html.RadioButton Exception

后端 未结 5 1491
梦毁少年i
梦毁少年i 2021-02-19 01:23

I haver a simple radio button list on my page that I render with the following in my view:


<%=         


        
5条回答
  •  天命终不由人
    2021-02-19 01:55

    You might want to try changing gender to a string (M/F) instead of an int and see if that works.

    If you absolutely must have it as an int, you could always translate on the back end.

    private int? gender { get; set; }
    public string displayGender
    {
        get
        {
            return this.gender.HasValue
                     ? (this.gender.Value == 1 ? "M" : "F" )
                     : null;
        }
        set
        {
            this.gender = null;
            if (value == "M")
               this.gender = 1;
            else if (value == "F")
               this.gender = 2;
        }
    }
    
    
    <%= Html.RadioButton("displayGender", "M") %> Male
    <%= Html.RadioButton("displayGender", "F") %> Female
    <%= Html.ValidationMessage("displayGender") %>
    

    Base on your comment, you may want to add:

    <%= Html.RadioButton("displayGender",
                         string.Empty,
                         true, // this is the default
                         new { @style = "display: none;" } ) %>
    

    This will ensure that displayGender gets posted back (there will always be a chosen radio) and I think the value will be string.Empty instead of a null reference. If this works, you may want to try switching back to the nullable int.

提交回复
热议问题