Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a checkbox in razor view?

I need to check a checkbox by default:

I tried all of these, nothing is checking my checkbox -

@Html.CheckBoxFor(m => m.AllowRating, new { @value = "true" })  @Html.CheckBoxFor(m => m.AllowRating, new { @checked = "true" })  @Html.CheckBoxFor(m => m.AllowRating, new { @checked = true })  @Html.CheckBoxFor(m => m.AllowRating, new { @checked = "checked"}) 
like image 987
kheya Avatar asked May 27 '11 20:05

kheya


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 do you check checkbox is checked or not?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);


2 Answers

You should set the AllowRating property to true, preferably in the controller or model.
Like other inputs, the checkbox's state reflects the value of the property.

like image 169
SLaks Avatar answered Sep 28 '22 23:09

SLaks


The syntax in your last line is correct.

 @Html.CheckBoxFor(x => x.Test, new { @checked = "checked" }) 

That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.

like image 36
Mark Avatar answered Sep 29 '22 00:09

Mark