[c#] MVC Razor Radio Button

In partial view I work with textboxes like this.

@model Dictionary<string, string>
@Html.TextBox("XYZ", @Model["XYZ"])

How can i generate radiobuttons, and get the desired value in the form collection as YES/NO True/False) ? Currently i am getting null for "ABC" if i select any value for the below.

   <label>@Html.RadioButton("ABC", @Model["ABC"])Yes</label>
   <label>@Html.RadioButton("ABC", @Model["ABC"])No</label>

Controller

        public int Create(int Id, Dictionary<string, string> formValues)
        {
         //Something Something
        }

This question is related to c# .net asp.net-mvc asp.net-mvc-3 razor

The answer is


I done this in a way like:

  @Html.RadioButtonFor(model => model.Gender, "M", false)@Html.Label("Male")
  @Html.RadioButtonFor(model => model.Gender, "F", false)@Html.Label("Female")

<label>@Html.RadioButton("ABC", "YES")Yes</label>
<label>@Html.RadioButton("ABC", "NO")No</label>

MVC Razor provides one elegant Html Helper called RadioButton with two parameters (this is general, But we can overload it uptil five parameters) i.e. one with the group name and other being the value

<div class="col-md-10">
    Male:   @Html.RadioButton("Gender", "Male")
    Female: @Html.RadioButton("Gender", "Female")
</div>                         

<p>@Html.RadioButtonFor(x => x.type, "Item1")Item1</p>
<p>@Html.RadioButtonFor(x => x.type, "Item2")Item2</p>
<p>@Html.RadioButtonFor(x => x.type, "Item3")Item3</p>

I solve the same problem with this SO answer.

Basically it binds the radio button to a boolean property of a Strongly Typed Model.

@Html.RadioButton("blah", !Model.blah) Yes 
@Html.RadioButton("blah", Model.blah) No 

Hope it helps!


I wanted to share one way to do the radio button (and entire HTML form) without using the @Html.RadioButtonFor helper, although I think @Html.RadioButtonFor is probably the better and newer way (for one thing, it's strongly typed, so is closely linked to theModelProperty). Nevertheless, here's an old-fashioned, different way you can do it:

    <form asp-action="myActionMethod" method="post">
        <h3>Do you like pizza?</h3>
        <div class="checkbox">
            <label>
                <input asp-for="likesPizza"/> Yes
            </label>
        </div>
    </form>

This code can go in a myView.cshtml file, and also uses classes to get the radio-button (checkbox) formatting.


<table>    
<tr>
                                        <td align="right" style="height:26px;">Is Calender Required?:</td>
                                        <td align="left">
                                            @Html.RadioButton("rdbCalenderRequested", "True", new { id = "rdbCalenderRequested_1" })@:Yes &nbsp;&nbsp;&nbsp; 

                                            @Html.RadioButton("rdbCalenderRequested", "False", new { id = "rdbCalenderRequested_2" }) @:No
                                        </td>

                                        <td align="right" style="height:26px;">Is Special Pooja?:</td>
                                        <td align="left">
                                            @Html.RadioButton("rdbPoojaRequested", "True", new { id = "rdbPoojaRequested_1" })@:Yes&nbsp;&nbsp;&nbsp; 

                                            @Html.RadioButton("rdbPoojaRequested", "False", new { id = "rdbPoojaRequested_2" }) @:No
                                        </td>
                                    </tr>
                                </table>

This works for me.

@{ var dic = new Dictionary<string, string>() { { "checked", "" } }; }
@Html.RadioButtonFor(_ => _.BoolProperty, true, (@Model.BoolProperty)? dic: null) Yes
@Html.RadioButtonFor(_ => _.BoolProperty, false, ([email protected])? dic: null) No

MVC5 Razor Views

Below example will also associate labels with radio buttons (radio button will be selected upon clicking on the relevant label)

// replace "Yes", "No" --> with, true, false if needed
@Html.RadioButtonFor(m => m.Compatible, "Yes", new { id = "compatible" })
@Html.Label("compatible", "Compatible")

@Html.RadioButtonFor(m => m.Compatible, "No", new { id = "notcompatible" })
@Html.Label("notcompatible", "Not Compatible")

Simply :

   <label>@Html.RadioButton("ABC", True)Yes</label>
   <label>@Html.RadioButton("ABC", False)No</label>

But you should always use strongly typed model as suggested by cacho.


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 .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

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 asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC