How do I set a checkbox in razor view?

2019-01-14 14:51发布

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"})

9条回答
可以哭但决不认输i
2楼-- · 2019-01-14 15:32

If we set "true" in model, It'll always true. But we want to set option value for my checkbox we can use this. Important in here is The name of checkbox "AllowRating", It's must name of var in model if not when we post the value not pass in Database. form of it:

@Html.CheckBox("NameOfVarInModel", true) ;

for you!

@Html.CheckBox("AllowRating", true) ;
查看更多
时光不老,我们不散
3楼-- · 2019-01-14 15:36

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.

查看更多
不美不萌又怎样
4楼-- · 2019-01-14 15:36

This works for me:

<input id="AllowRating" type="checkbox" checked="@Model.AllowRating" 
style="" onchange="" />

If you really wants to use HTML Helpers:

@Html.CheckBoxFor(m => m.AllowRating, new { @checked = Model.AllowRating})
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-14 15:41

I did it using Razor , works for me

Razor Code

@Html.CheckBox("CashOnDelivery", CashOnDelivery) (This is a bit or bool value) Razor don't support nullable bool
@Html.CheckBox("OnlinePayment", OnlinePayment)

C# Code

 var CashOnDelivery = Convert.ToBoolean(Collection["CashOnDelivery"].Contains("true")?true:false);
 var OnlinePayment = Convert.ToBoolean(Collection["OnlinePayment"].Contains("true") ? true : false);
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-14 15:45

you set AllowRating property to true from your controller or model

      @Html.CheckBoxFor(m => m.AllowRating, new { @checked =Model.AllowRating })
查看更多
贪生不怕死
7楼-- · 2019-01-14 15:45

I had the same issue, luckily I found the below code

@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )

Check Box Checked By Default - Razor Solution

查看更多
登录 后发表回答