-1

I'm using asp.net MVC 5 i want to set a check box as default but I'm failing to achieve this, in a razor.

I tried even this link:

How do I set a checkbox in razor view?

Controller

 Active = memberViewModel.active

view

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

Viewmodel

 public bool active { get; set; }
Community
  • 1
  • 1
sibonile
  • 109
  • 1
  • 1
  • 10

1 Answers1

3

Your binding to a property so the checkbox state is determined from the value of the property. In your controller, set the value of active to true (or set it in a parameterless constructor of the class), and then in the view

@Html.CheckBoxFor(model => model.active)
  • I don't understand your comment. If the value of property `isactive` is set to `true` when you pass the model to the view, the checkbox **will** be checked. Are you even passing the model to the view? –  Feb 06 '15 at 08:35
  • yes i did set active to true my problem is that the checkbox is not checked on the view – sibonile Feb 06 '15 at 08:47
  • Thats got nothing to do with it! You need to set the value either in a parameterless constructor - e.g. `public class MyModel { public MyModel() { active = true; } public bool active { get; set; } }` or set it's value in the controller before you pass the model to the view - e.g.`MyModel model = new MyModel(); model.active = true; return View(model);` –  Feb 06 '15 at 08:53
  • And from the [documentation](https://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute%28v=vs.110%29.aspx) _A DefaultValueAttribute will **not** cause a member to be automatically initialized with the attribute's value. You **must** set the initial value in your code._ –  Feb 06 '15 at 08:56