(C# ASP.NET Core) CRUD with a Radiobuttonlist in a Razor Form

This tutorial extends the FORM that we have implemented in the previous tutorial (see link below). Now we add a radiobuttonlist to that form and observe how easy is it to make an addition to a project that is already CRUD-ready! The radiobuttonlist is backed by a hard-coded C# enumeration. We also explain how to specify the conversion from an enum to an INT data-type on the database side.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Objective of this Tutorial

This tutorial adds a radiobuttonlist to the form that we completed in the previous tutorial (C# ASP.NET Core) CRUD with a Checkbox in a Razor Form

C# Enumeration for RadiobuttonList

Radio-button-lists are backed by a collection - which is usually small - otherwise we risk making the form too bulky. They backing collection can either be hard-coded as, say, an enumeration, or maintained in an XML file.

In this tutorial we shall back our radiobuttonlist with a hard-coded enumeration. The enum can be defined in the model class itself, and a corresponding property can be added to the backing class as suggested below.

public class YourModel
{


  // other props . . . 

  // enum for radio 
  public enum Quality
  {

    Superior = 0,
    Inferior = 1,
    Normal = 2,
  }


  // property  for radio button list 
  public int ItemQuality { get; set; }
}

The conversion from C# side enumeration to the database-side of the corresponding column has to be specified in the OnModelCreating method of the DbContext class. See the extract below.

// dbcontext DAL - THERE IS ONE DbContext per database 
public class ProductContext : DbContext
{


  // . . . other parts of the class 

  // this function is used to specify FK relations, Indexes, 
  // and [optionally] the name of your database tables 
  // corresponding to each model 
  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {

    base.OnModelCreating(modelBuilder);

    // name of the table in your database 
    modelBuilder.Entity<Product>().ToTable("product");

    // ADD THIS 
    modelBuilder
    .Entity<Product>()
    .Property(p => p.ItemQuality)
    .HasConversion<int>();

  }


  // . . . other parts of the class 
}

Video Explanation

Please watch the following youtube video:

Generating a RadiobuttonList from the C# Enumeration

A foreach loop must be used to loop over the enumeration.


@foreach (var item in System.Enum.GetValues(typeof(Product.Quality)))
{

  <label>

    <input  type="radio" 
            asp-for="Prod.ItemQuality" 
            value="@Convert.ToInt32(item)" />

    @item

  </label>

}

Step 1 of 3: Modify the Model

Our radio-button list will be backed by a hard-coded enumeration.

Add an enum and a field to your model class. Nothing else needs to be changed.

public class Product
{

  // auto-increment Primary ID key 
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ID { get; set; }

  // binds to a textbox 
  public String Name { get; set; }

  // a checkbox boolean 
  public bool IsActive { get; set; }

  // ADD THIS NOW: enum for radio 
  public enum Quality
  {

    Superior = 0,
    Inferior = 1,
    Normal = 2,
  }


  // ADD THIS NOW  for radio button list 
  public int ItemQuality { get; set; }
}

Step 2 of 3: Specify Enum to int Conversion

Modify the OnModelCreating method of the ProductContext class, so that the final class looks like this:

// dbcontext DAL 
public class ProductContext : DbContext
{

  public ProductContext(DbContextOptions options) : base(options)
  {

    // EnsureCreated is meant for testing or creating 
    // a blank database. this code should be avoided 
    // at this place. use some alternate program to 
    // create/migrate your database. this code has been 
    // used here only for tutorial purposes 
    Database.EnsureCreated();

  }

  // this function is used to specify FK relations, Indexes, 
  // and [optionally] the name of your database tables 
  // corresponding to each model 
  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {

    base.OnModelCreating(modelBuilder);

    // name of the table in your database 
    modelBuilder.Entity<Product>().ToTable("product");

    // ADD THIS 
    modelBuilder
    .Entity<Product>()
    .Property(p => p.ItemQuality)
    .HasConversion<int>();

  }

  // MUST be PLURAL 
  public DbSet<Product> Products { get; set; }
}

Step 3 of 3: Modify the Razor FORM

use a for-each loop to add input tags for the radiobuttons.


// index.cshtml razor page completed 

@page "{handler?}/{id?}"

@namespace DBaseCon

@model Modular.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<form method="post">

  Name: <input asp-for="Prod.Name" />

  <input asp-for="Prod.ID" type="hidden" />

  <br />

  <label asp-for="Prod.IsActive">Active</label>

  <input asp-for="Prod.IsActive" />

  <br />

 // add a radio for "None".  
  <label>
    
    <input  type="radio" 
            asp-for="Prod.ItemQuality" 
            value="-1" 
            checked />

    None

  </label>

 // foreach over the enumeration to add radiobuttonlist 
  @foreach (var item in System.Enum.GetValues(typeof(Product.Quality)))
  {

    <label>

      <input  type="radio" 
              asp-for="Prod.ItemQuality" 
              value="@Convert.ToInt32(item)" />

      @item

    </label>

  }

 // if "None" is moved here then you may have 
 // to set the checked property depending on 
 // whether the mode is edit or insert 

  <br />

  <input type="submit" />

</form>

<h1>Display of Data</h1>

@foreach (var prod in Model.Products)
{
  <div>

    @prod.Name,
    @(prod.IsActive ? "Active" : "In-Active"),
    @System.Enum.GetValues(
      typeof(Product.Quality)).GetValue(prod.ItemQuality)

    |

    <a asp-route-id="@prod.ID"
       asp-page-handler="Delete">Delete</a>

    |

    <a asp-route-id="@prod.ID"
       asp-page-handler="Edit">Edit</a>

  </div>

  <hr />
}
In this case of our tutorial simply delete your sqlite database file (mydb.db) and allow the DbContext to re-create it from the modified model class.

WHY WAS IT SO SIMPLE?

Ans: Right from the creation of database till the CRUD operations, the EF Core framework works on the basis of your model class. You just have to add a property to your model class + a corresponding input tag helper to your form, and make no change anywhere else. In simple words: The property travels everywhere with the model.


This Blog Post/Article "(C# ASP.NET Core) CRUD with a Radiobuttonlist in a Razor Form" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.