2

I am having radio button for Male and Female Option but problem is they both are selected instead of any one.

My Controller:

 private List<SelectedGenderModel> GetGender()
        {
            var gender = new List<SelectedGenderModel>();
            gender.Add(new SelectedGenderModel { Name = "Male", Id = 1, Selected = false });
            gender.Add(new SelectedGenderModel { Name = "Female", Id = 2, Selected = false });
            return gender;
        }

My View:

@model MvcDemo.Models.EmployeeModel
 @for (int i = 0; i < Model.Gender.Count; i++)
                {
                    @Html.RadioButtonFor(m => m.Gender[i].Selected, new { id = "gender_" + i, name = "gendernm_" })
                    @Html.HiddenFor(m => m.Gender[i].Id)
                    @Html.HiddenFor(m => m.Gender[i].Name)
                    @Html.DisplayFor(m => m.Gender[i].Name)
                }

My View Model:

public class EmployeeModel
    {
            public int Id { get; set; }
            public string Fullname { get; set; }
            public List<SelectedGenderModel> Gender { get; set; }
    }

My Data Model:

public partial class EmployeeMaster
    {
        public int Id { get; set; }
        public string Fullname { get; set; }
        public Nullable<bool> Gender { get; set; }
    }

So How do i prevent from multiple selection of radio button??

I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216
  • In each loop you only render one radio button. They are in different groups! And why do you need a model for this (as opposed to just binding to a property `string Gender` with 2 radio buttons for Male and Female)? –  Feb 23 '15 at 05:50
  • i will store 0 and 1 for gender and i have created model for gender to get selected gender based on radio button selected – I Love Stackoverflow Feb 23 '15 at 05:53
  • Then include a property `int Gender { get; set; }` and bind 2 radio buttons to that property (but why would you use `0` or `1`? - make it a string or an enum instead). None of the code you have shown is necessary. –  Feb 23 '15 at 05:57
  • should i post you my view model and data model?? – I Love Stackoverflow Feb 23 '15 at 06:00
  • Include you view model, and I'll post an answer shortly showing how to do this. –  Feb 23 '15 at 06:01

1 Answers1

1

Your loop is rendering 2 radio buttons with different names (name="Gender[0].Selected" and name="Gender[1].Selected") which means they belong to 2 different groups. You may think that new { name = "gendernm_" } is modifying the name attribute, but fortunately it isn't (otherwise model binding would fail on post back).

Is unclear why you data model has property bool? Gender (is a value of true supposed to mean Male or Female? and what does a null value mean? Perhaps bool IsMale or bool IsFemale might make more sense to someone else, but why not just make it a string (or an enum)?

Change your view model to

public class EmployeeModel
{
  public int Id { get; set; }
  public string Fullname { get; set; }
  [Required]
  public string Gender { get; set; }
}

and in the view

@Html.RadioButtonFor(m => m.Gender, "Male", new { id = "Male" })
<label for"Male">Male</label>
@Html.RadioButtonFor(m => m.Gender, "Female", new { id = "Female" })
<label for"Female">Female</label>
@Html.ValidationMessageFor(m => m.Gender)

If you do want to make it nullable bool, then you can use

@Html.RadioButtonFor(m => m.Gender, "True", new { id = "Male" })
<label for"Male">Male</label>
@Html.RadioButtonFor(m => m.Gender, "False", new { id = "Female" })
<label for"Female">Female</label>
@Html.RadioButtonFor(m => m.Gender, "", new { id = "Unknown" })
<label for"Unknown">Not sure</label>
  • but dont you think that storing Male or Female in Tables is just a waste of storage – I Love Stackoverflow Feb 23 '15 at 06:29
  • your solution is good but here you have written two time radiobutton for as because you know there are 2 options i.e male and female.but what if values for radio button are coming from database then.like assume Male and female are coming from database or from a server side like i have shown in my method then?? – I Love Stackoverflow Feb 23 '15 at 06:33
  • 1
    Of course not. Its insignificant (and you could always make it `char(1)` and store the values as "M" and "F" (2 bytes). Readability is far more important here and who other than your self could understand what `Gender=true` is supposed to mean. –  Feb 23 '15 at 06:34
  • Yes you are right but what would you like to say about my second comment? – I Love Stackoverflow Feb 23 '15 at 06:37
  • @MariaPithia, If in the first example ("Male" or "Female"), if the value in the database is "Female" (i.e. `model.Gender="Female"`), then the 2nd option will be selected (that's how model binding works). Similarly, if you stored it as just "M" or F", then change the 2nd parameter of the `RadioButtonFor()` to "M" and "F" respectively and you will get 2-way binding. –  Feb 23 '15 at 06:37
  • my problem is why you have written 3 times radio button for as because you know that there are 3 values.render radio buttons in such a way as you dont know how many options are there.like suppose you are creating online examination and you are rendering options of particular question then in that case you dont know how many options will be there for particular questions and so you have you use for loop for that – I Love Stackoverflow Feb 23 '15 at 06:42
  • That's a different question, but the answers [here](http://stackoverflow.com/questions/24726993/get-the-selected-values-of-radio-button-in-mvc/24728347#24728347) and [here](http://stackoverflow.com/questions/28254213/razor-binding-issue-with-radio-button/28258238#28258238) and [here](http://stackoverflow.com/questions/28261429/all-radio-buttons-are-grouped-together-for-all-the-items-in-the-model-list/28261523#28261523) are all related to that. –  Feb 23 '15 at 06:50
  • 1 thing i dont understand is how this radio buttonfor works.like how it binds value in model – I Love Stackoverflow Feb 23 '15 at 07:13
  • 1
    If you have a property say `string SelectedAnswer { get; set; }` and the value of `SelectedAnswer` is say `"Answer 1"`, then if you have `@Html.RadioButtonFor(m => m.SelectedAnswer", "Answer 1", ...)`, then that radio button will be selected (the value of the property matches the value of the 2nd parameter of the helper - that's how model binding works) –  Feb 23 '15 at 07:18
  • can you edit your code and show me same thing with foreach loop and also when i will open particular employee recordd in edit mode then i want my particular radio button to be selected(Either Male or Female) with the same view.is that possible?? – I Love Stackoverflow Feb 23 '15 at 07:25
  • It does not make any sense to have a `for` loop in this case. And all you need to do is set the property `model.Gender="Male";` in the controller before you return the view and you will see that the first radio button will be selected –  Feb 23 '15 at 07:28
  • i am just asking for learning purpose.i do know that for loop doesnt require in this case.but just for learning purpose if you can show this with for loop – I Love Stackoverflow Feb 23 '15 at 07:33
  • 1
    @MariaPithia, I gave you links to 3 answers showing how to use a for loop in one of my comments above. In this case, if you have a property `public List GenderList { get; set; }` which contained `{ "Male", Female" }` then you could do `foreach(var gender in Model.GenderList) { @Html.DropDownListFor(m => m.Gender, gender, new { id = gender })` –  Feb 23 '15 at 07:39
  • for (int i = 0; i < Model.Gender.Count; i++) { @Html.RadioButtonFor(m => m.SelectedGender, Model.Gender[i].Selected) @Html.HiddenFor(m => m.Gender[i].Name) @Html.DisplayFor(m => m.Gender[i].Name) } – I Love Stackoverflow Feb 23 '15 at 09:21
  • when i am selecting male option then i am getting false value – I Love Stackoverflow Feb 23 '15 at 09:21
  • public string SelectedGender { get; set; } is in Employee model – I Love Stackoverflow Feb 23 '15 at 09:27
  • @MariaPithia, If you cant follow the code I gave you then I not sure how else to help. I don't know what `Model.Gender[i].Selected` is supposed to be - if its from the 1st code snippet in your question then your always rendering "false" (both items in the list have `Selected=false`, which should be obvious if you check the html your generating) so that's what it will be. And why are you using `@Html.DisplayFor()`? (you should be creating a label associated with the button). I really don't understand why you want to take a simple concept and make it overly complicated. –  Feb 23 '15 at 09:33
  • can you create a chat so that we can discuss.I wont take your much time – I Love Stackoverflow Feb 23 '15 at 09:35
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/71471/discussion-between-stephen-muecke-and-maria-pithia). –  Feb 23 '15 at 09:36