How to have ASP.Net MVC 3.0 Checkboxfor as checked by default?

HaBo picture HaBo · Oct 19, 2011 · Viewed 11.8k times · Source

I want mt view to have the check box checked by default, I tried something like this.

@Html.CheckBoxFor(model=>model.GenericsOK, new { id = ViewBag.GenericsOK, @checked = true })

and also

@Html.CheckBoxFor(model=>model.GenericsOK, new { id = ViewBag.GenericsOK, @checked = "checked"})

in both cased it give the below error. String was not recognized as a valid Boolean.

My property is defined as this.

private bool _deafaultchecked = true;

    [Display(Name = "Generics Ok")]
    public bool GenericsOK
    {
        get { return _deafaultchecked; }
        set { _deafaultchecked = value; }
    }

any suggestions please?



Since i could not find a solution or this. i got this done like this.

 @Html.CheckBox("GenericsOK", true, new {id=ViewBag.GenericsOK, name="GenericsOK" })

this works for my requirement. thanks for all who helped me.

Answer

qsoft picture qsoft · Jun 13, 2012

In your controller's Create method (I presume), have you tried this?

public ActionResult Create()
{
    return View(new YourModelClass { GenericsOk = true });
}