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条回答
相关推荐>>
2楼-- · 2019-01-14 15:48

only option is to set the value in the controller, If your view is Create then in the controller action add the empty model, and set the value like,

Public ActionResult Create()
{
UserRating ur = new UserRating();
ur.AllowRating = true;
return View(ur);
} 
查看更多
等我变得足够好
3楼-- · 2019-01-14 15:51

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.

查看更多
够拽才男人
4楼-- · 2019-01-14 15:55

You can do this with @Html.CheckBoxFor():

@Html.CheckBoxFor(m => m.AllowRating, new{@checked=true });

or you can also do this with a simple @Html.CheckBox():

@Html.CheckBox("AllowRating", true) ;
查看更多
登录 后发表回答