Set a label value for a checkbox helper in asp.net mvc

675 Views Asked by At

I am developping an asp.net mvc application.

I have a viewmodel :

public class UserViewModel
{
    public bool IsActive {get;set;}
}

And I have the associated razor view :

<span>@Html.CheckBoxFor(d => d.IsActive)</span>

The problem with this is that I have only the checkbox in my view without any label, I would like to know if it's possible to indicate a label in the CheckBoxFor parameter or by adding an attribute on my property in the ViewModel.

2

There are 2 best solutions below

0
On

You can use Data Annotations. Add this at the top of your ViewModel class definition

using System.ComponentModel.DataAnnotations;

Add [Display(Name = "Active")] above the IsActive property

public class UserViewModel
{
    [Display(Name = "Active")]
    public bool IsActive {get;set;}
}        

and add @Html.LabelFor(d => d.IsActive) in your view

@Html.LabelFor(d => d.IsActive)<span>@Html.CheckBoxFor(d => d.IsActive)</span>

which will render <label for="IsActive">Active</label> before the checkbox.

0
On

Try like below :

Add below namespace in your ViewModel

using System.ComponentModel.DataAnnotations;

Then use [Display(Name="Sample Label Text")] above class property.

public class UserViewModel
{
    [Display(Name = "Sample Label Text")]
    public bool IsActive {get;set;}
}

At last use @Html.LabelFor to render it

<span>@Html.LabelFor(d => d.IsActive)</span>
<span>@Html.CheckBoxFor(d => d.IsActive)</span>