Ash
Ash

Reputation: 3532

ASP.NET MVC using bool value for radio button checked property

Basically I want my radio buttons to be checked depending on a value from my model view control, below is some sample code and my attempt so far:

  <tr>
                <td>
                <label for="brakepads" class="label3">Brake Pads:</label></td>
                <%= Html.TextBox("brakepads", Model.brakepads, new {style="display:none" })%>
                <%= Html.ValidationMessage("brakepads", "*") %>

                <td><label for="brakefluid" class="label4" >Passed:</label>
                <asp:RadioButton ID="RadioButton15" runat="server" GroupName="b" value="True" Checked="<%= Model.brakepads.Value %>" onclick="brakepads.value=(this.value)" /></td>
                <td><label for="brakefluid"  class="label4" >Failed:</label>
                <asp:RadioButton ID="RadioButton16" runat="server" GroupName="b" value="False" Checked="<% Model.brakepads.Value %>" onclick="brakepads.value=(this.value)"/></td>
                </tr>

I get the following at runtime: Cannot create an object of type 'System.Boolean' from its string representation '<%= Model.brakepads.Value %>' for the 'Checked' property.

I tried using (bool) to cast, but that didn't work either, so I'm unsure of what to do next. My only concern is that occasionally the bool will be null, if that won't break functionality then it's fine.

Upvotes: 3

Views: 15459

Answers (3)

wayne.blackmon
wayne.blackmon

Reputation: 761

How to do a boolean radio button list in ASP.NET MVC 3 razor C#

What we want the html to be

Apply discount: 
<input type="radio" name="apply_discount" value="yes" /> Yes
<input type="radio" name="apply_discount" value="no" /> No

We need a model property

public bool ApplyDiscount { get; set; }

Now all we have to do is convert the html to razor

Apply discount:
@Html.RadioButtonFor(m => m.ApplyDiscount, true) Yes
@Html.RadioButtonFor(m => m.ApplyDiscount, false) No

I hope this helps.

Upvotes: 8

Priyank
Priyank

Reputation: 10623

Either you use Html.RadioButton or have another MVC hidden field and bind Model.brakepads to it. Use javascript to set radio button's Checked property.

Upvotes: 0

Zruty
Zruty

Reputation: 8667

You are mixing WebForms controls (RadioButton) together with ASP.NET MVC helpers (Html.TextBox), I think it's a dangerous practice.

You could try using Html.RadioButton() helper method to render a radio button:

<td><label for="brakefluid" class="label4" >Passed:</label>
<%= Html.RadioButton("brakefluid", true, Model.brakepads.Value) %></td>
<td><label for="brakefluid"  class="label4" >Failed:</label>
<%= Html.RadioButton("brakefluid", false, !Model.brakepads.Value) %></td>    

Upvotes: 2

Related Questions