start a group of radiobuttons unchecked in asp.net mvc
Asked Answered
B

1

6

Hólla everybody,

I have a strongly typed view and for one int Rating property, I am generating few radio buttons like so:

@Html.RadioButtonFor(m => m.Rating, 1, new { id = "past_Rating_one"})
@Html.RadioButtonFor(m => m.Rating, 2, new { id = "past_Rating_two"})
@Html.RadioButtonFor(m => m.Rating, 3, new { id = "past_Rating_three"})
@Html.RadioButtonFor(m => m.Rating, 4, new { id = "past_Rating_four"})
@Html.RadioButtonFor(m => m.Rating, 5, new { id = "past_Rating_five"})

of course, I be having labels after each radio button and jquery be fancying it with images and such wonders.

All this is fine, but when the page starts, the radio button with id past_Rating_one be selected already. I be bewildered as to how to start all radio buttons unchecked when page loads.

Sure, can do with jQuery but I want to do it just with the view.

I tried it with this:

@Html.RadioButtonFor(m => m.Rating, 1, new { id = "past_Rating_one", selected="none"})

firebug inspection shows that as a property, but still that darn radio button (first one) be stubbornly checked, so I thought I would seek yer help.

Bernice answered 22/8, 2011 at 16:17 Comment(0)
D
10

Try setting Rating as a nullable object in your viewmodel, like:

int? Rating { get; set; }

An integer defaults to zero, so value 0 will be selected when rendering the radiobuttons. I know in your example you don't use the value 0, but I suspect you do in your project. Otherwise I could not think of reason the radiobutton is selected.

In case Rating is an enum, the same thing applies.

Downtoearth answered 22/8, 2011 at 17:13 Comment(4)
Robin, you mention if it's an enum then the same thing applies. I get an error if I do public MyEnum? MyProperty { get; set;}. I am having the same problem with the first thing in my radio button list being default selected, and I want them to all be blank on page load. Any ideas? Thanks.Catacaustic
@Catacaustic I know this is old, but I am using an nullable Enum and it works perfectly for me. What error are you getting?Ganymede
@Ganymede Problem resolved. Instead of int? Rating for example, I might do RatingEnum? Rating.Catacaustic
What if I have an enum with 3 values, but I want to display only 2 rado buttons, and when none of the, is selected then I would expect the fisrt value form an enum: 'Enum X{ A,B,C}' radio button for B and for C, but none of the selected the model property would be value AArdra

© 2022 - 2024 — McMap. All rights reserved.