Question

I am developing an ASP.Net MVC 3 Web Application using Razor Views. Within the View I would like to ask the user a question which can only have a Yes/ No answer, therefore, I am planning on using two Radio Buttons.

I have a ViewModel which I pass to my View, and it looks like this

public class ViewModelFormImmigration
{
    public int immigrationID { get; set; }
    public int formID { get; set; }

    [Required(ErrorMessage = "Please select Yes or No.")]
    public bool euNational { get; set; }
}

In my View I then have the following lines of code to display the radio buttons for both the Yes and No options

@Html.RadioButtonFor(model => model.euNational, true) <text>Yes</text>
@Html.RadioButtonFor(model => model.euNational, false) <text>No</text>

My problem is that, when the User comes to this View for the first time, I would like neither the Yes or No option selected. At the moment, when I create an instance of my ViewModel (see above), the property euNational is defaulted to false and when the ViewModel is passed to my View, this means that the option No is automatically selected.

Is there anyway around this so that when the User see's the View for the first time, that no option is not selected by default?

Thanks for your help everyone.

Was it helpful?

Solution

Try changing:

[Required(ErrorMessage = "Please select Yes or No.")]
public bool euNational { get; set; }

To:

[Required(ErrorMessage = "Please select Yes or No.")]
public bool? euNational { get; set; }

This way, when you first load the view with no value set for euNational it will not set to neither true or false. As at the moment when it has no value set, it defaults to false

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top