[c#] ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Does anyone know how to bind a Yes/No radio button to a boolean property of a Strongly Typed Model in ASP.NET MVC.

Model

public class MyClass
{
     public bool Blah { get; set; }
}

View

<%@  Page Title="blah"  Inherits="MyClass"%>
    <dd>
        <%= Html.RadioButton("blah", Model.blah) %> Yes
        <%= Html.RadioButton("blah", Model.blah) %> No
    </dd>

Thanks

SOLUTION:

Thanks for Brian for the direction but it was the opposite of what he wrote. As so -

<%@  Page Title="blah"  Inherits="MyClass"%>
<dd>
    <%= Html.RadioButton("blah", !Model.blah) %> Yes
    <%= Html.RadioButton("blah", Model.blah) %> No
</dd>

This question is related to c# asp.net-mvc model radio-button boolean

The answer is


Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.


Here is a more complete example using a fieldset for accessibility reasons and specifying the first button as the default. Without a fieldset, what the radio buttons are for as a whole can not be programmatically determined.

Model

public class MyModel
{
    public bool IsMarried { get; set; }
}

View

<fieldset>
    <legend>Married</legend>

    @Html.RadioButtonFor(e => e.IsMarried, true, new { id = "married-true" })
    @Html.Label("married-true", "Yes")

    @Html.RadioButtonFor(e => e.IsMarried, false, new { id = "married-false" })
    @Html.Label("married-false", "No")
</fieldset>

You can add a @checked argument to the anonymous object to set the radio button as the default:

new { id = "married-true", @checked = 'checked' }

Note that you can bind to a string by replacing true and false with the string values.


or MVC 2.0:

<%= Html.RadioButtonFor(model => model.blah, true) %> Yes
<%= Html.RadioButtonFor(model => model.blah, false) %> No

Building slightly off Ben's answer, I added attributes for the ID so I could use labels.

<%: Html.Label("isBlahYes", "Yes")%><%= Html.RadioButtonFor(model => model.blah, true, new { @id = "isBlahYes" })%>
<%: Html.Label("isBlahNo", "No")%><%= Html.RadioButtonFor(model => model.blah, false, new { @id = "isBlahNo" })%>

I hope this helps.


If I can throw my hat into the ring, I think there is a cleaner way than the existing answers to reuse the radio button functionality.

Let's say you have the following property in your ViewModel:

Public Class ViewModel
    <Display(Name:="Do you like Cats?")>
    Public Property LikesCats As Boolean
End Class

You can expose that property through a reusable editor template:

First, create the file Views/Shared/EditorTemplates/YesNoRadio.vbhtml

Then add the following code to YesNoRadio.vbhtml:

@ModelType Boolean?

<fieldset>
    <legend>
        @Html.LabelFor(Function(model) model)
    </legend>

    <label>
        @Html.RadioButtonFor(Function(model) model, True) Yes
    </label>
    <label>
        @Html.RadioButtonFor(Function(model) model, False) No
    </label>
</fieldset>

You can call the editor for the property by manually specifying the template name in your View:

@Html.EditorFor(Function(model) model.LikesCats, "YesNoRadio")

Pros:

  • Get to write HTML in an HTML editor instead of appending strings in code behind.
  • Preserves the DisplayName DataAnnotation
  • Allows clicks on Label to toggle radio button
  • Least possible code to maintain in form (1 line). If something is wrong with the way it is rending, take it up with the template.

If you're using MVC 3 and Razor you can also use the following:

@Html.RadioButtonFor(model => model.blah, true) Yes
@Html.RadioButtonFor(model => model.blah, false) No

I ended up packaging this into an extension method so (1) I could generate the label and radio at once and (2) so I didn't have to fuss with specifying my own IDs:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString RadioButtonAndLabelFor<TModel, TProperty>(this HtmlHelper<TModel> self, Expression<Func<TModel, TProperty>> expression, bool value, string labelText)
    {
        // Retrieve the qualified model identifier
        string name = ExpressionHelper.GetExpressionText(expression);
        string fullName = self.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

        // Generate the base ID
        TagBuilder tagBuilder = new TagBuilder("input");
        tagBuilder.GenerateId(fullName);
        string idAttr = tagBuilder.Attributes["id"];

        // Create an ID specific to the boolean direction
        idAttr = String.Format("{0}_{1}", idAttr, value);

        // Create the individual HTML elements, using the generated ID
        MvcHtmlString radioButton = self.RadioButtonFor(expression, value, new { id = idAttr });
        MvcHtmlString label = self.Label(idAttr, labelText);

        return new MvcHtmlString(radioButton.ToHtmlString() + label.ToHtmlString());
    }
}

Usage:

@Html.RadioButtonAndLabelFor(m => m.IsMarried, true, "Yes, I am married")

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to model

Eloquent ORM laravel 5 Get Array of ids Tensorflow: how to save/restore a model? Cannot overwrite model once compiled Mongoose AngularJS - Binding radio buttons to models with boolean values Accessing MVC's model property from Javascript MVC 4 - how do I pass model data to a partial view? How to load json into my angular.js ng-model? Check if an object exists CodeIgniter PHP Model Access "Unable to locate the model you have specified" Removing a model in rails (reverse of "rails g model Title...")

Examples related to radio-button

Angular 4 default radio button checked by default Angular2 - Radio Button Binding Detect if a Form Control option button is selected in VBA How to create radio buttons and checkbox in swift (iOS)? How to check if a radiobutton is checked in a radiogroup in Android? Radio Buttons ng-checked with ng-model Multiple radio button groups in MVC 4 Razor Show div when radio button selected Check a radio button with javascript Bootstrap radio button "checked" flag

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas