Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the default radio button to be unchecked while using Razor in MVC?

I am using radio button like this,

 <div class="form-group">
                @Html.LabelFor(x => x.gender)
                <div class="form-check">
                    <label class="form-check-label">
                        @Html.RadioButtonFor(x => x.gender, "Male")
                        Male
                    </label>
                </div>
                <div class="form-check">
                    <label class="form-check-label">
                        @Html.RadioButtonFor(x => x.gender, "Female")
                        Female
                    </label>
                </div>
            </div>

here i have two radio button which is rendered in the page, i want the radio button to be rendered and without the default selection of any of the radio button, how can i do this

i tried like this but it is not working

 @Html.RadioButtonFor(x => x.gender, "Female", new { @checked = "true" })

UPDATE

public class student
    {             
        [DisplayName("Gender")]
        [Required(ErrorMessage = "please select gender")]
        public gender gender { get; set; }
    } 

public enum gender
    {
        male,
        female
    }
like image 534
Lijin Durairaj Avatar asked Mar 07 '23 03:03

Lijin Durairaj


1 Answers

To make sure nothing is selected by default, make your property nullable:

public gender? gender { get; set; }

Its default value will be null, and that will make sure nothing is selected, but Required attribute won't allow null as valid value once user posted the form.

On a separate note, you are using strings as values right now, I am not sure that is going to work with enum at all. It would be much better to do something along these lines:

@Html.RadioButtonFor(x => x.gender, gender.Female)
@Html.Label(gender.Female.ToString())
// Or you can stick to literals for labels as you do now.
// This however allows you to eventually turn this rendering code into a loop
like image 76
Andrei Avatar answered May 01 '23 16:05

Andrei