Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Label for checkbox in razor

How does one set the label of a checkbox? I looked at some sites and they are using lambda expressions, but I can't understand them. I am new to asp.net MVC.

@{    bool chkVal = false;    } <li>@Html.CheckBox("chksumma",chkVal,new {@value = "5"})</li> <li>@Html.LabelFor(, ""); 
like image 485
Vignesh Avatar asked Jul 13 '13 01:07

Vignesh


People also ask

How do you bind a checkbox in MVC 4 Razor?

Here Data Source is Server Name and Initial Catalog is database Name. Now open home controller and write following code in it. Add the namespace using BindCheckBoxUsingMVC. Models on the top.As this namespace contains DbAccess and Sports Class.

How to use checkbox in Razor page?

Razor offers two ways to generate checkboxes. The recommended approach is to use the input tag helper. Any boolean property of the PageModel will render a checkbox if it is passed to the asp-for attribute, so long as the property is not nullable: public class IndexModel : PageModel.

What is HTML Labelfor?

Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression): // Model public string Test { get; set; } // View @Html. Label("Test") // Output <label for="Test">Test</label>

How do I add a checkbox to a label in HTML?

The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices. Tip: Always add the <label> tag for best accessibility practices!


1 Answers

This is a really good way:

<div class="checkbox">     <label>@Html.CheckBoxFor(x => item.IsSelected)&nbsp;@Html.DisplayNameFor(x => item.IsSelected)</label> </div> 

Check box with label

  1. It's what is recommended by bootstrap 3.
  2. It works in a table.
  3. You can click on the check box OR the label to select the box. (This is an important usability feature.)
  4. The cursor is properly the "hand" instead of the arrow pointer.

EDIT

This is really easy to do in Bootstrap 4.

You just wrap your label and input inside form-check markup:

<div class="form-check">   <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">   <label class="form-check-label" for="defaultCheck1">Default checkbox</label> </div> 
like image 117
Jess Avatar answered Oct 21 '22 02:10

Jess