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

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.

Answers


You will want to remove the @checked="checked" portion of the HTML attributes. If the viewmodel property is a boolean then it is unnecessary when you use the CheckBoxFor


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

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

In the controller action where you create the model just set that field value to true.

For example

return View(new DriverCsvModel{SendEmails = true});

You should be using the state of the model, rather than forcing the UI into a checked state.


In the default constructor for your model class, you can set the "GenericsOK" property to "True"


Need Your Help

Passing a Mongo ObjectId in a URL and querying that ID with Node/Express

node.js mongodb express

I'm having a lot of trouble passing in an objectId as my URL parameter. I know that the ObjectId in MongoDB is a hex value, and that I need to do some conversions, but I'm getting errors with every

Can't display PDF from HTTPS in IE 8 (on 64-bit Vista)

internet-explorer pdf internet-explorer-8 https 64bit

I have a home-grown HTTPS server that serves up simple files (it's embedded within my app). It works great -- been using it forever.