Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a CheckBox by default Checked in ASP.Net MVC

I am using CheckBox in my ASP.Net MVC project,

i want to set checkBox by default checked,

My CheckBox is

@Html.CheckBoxFor(model => model.As, new { @checked = "checked" }) 

but its not working,,,,

like image 986
Avinash Singh Avatar asked May 08 '13 07:05

Avinash Singh


People also ask

How to make checkbox default Checked in mvc?

The correct way to achieve that is to set the value in the controller. That's how the CheckBoxFor helper is designed to be used. If you don't want to follow the best practices you could always manually generate the checkbox in the view with a hardcoded checked="checked" attribute.

How to make CheckBox Checked by default in asp net?

Hi akhter, Set the CheckBox Checked property to true and Enabled property to false. This will set default check on all rows in GridiVew and can not uncheck CheckBox.

How to set CheckBox Checked in mvc razor?

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.


2 Answers

In your controller action rendering the view you could set the As property of your model to true:

model.As = true; return View(model); 

and in your view simply:

@Html.CheckBoxFor(model => model.As); 

Now since the As property of the model is set to true, the CheckBoxFor helper will generate a checked checkbox.

like image 100
Darin Dimitrov Avatar answered Sep 20 '22 19:09

Darin Dimitrov


Old question, but another "pure razor" answer would be:

@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} ) 
like image 21
tonjo Avatar answered Sep 17 '22 19:09

tonjo