Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting html attribute that is reserved keyword in Html.CheckBoxFor in ASP.NET MVC

I am using the HtmlHelper to create a checkbox in my view like so:

<%= Html.CheckBoxFor(model => model.SeatOnly, new { checked = "checked" })%>

However, an error is being thrown as checked is a reserved keyword. I have found a couple of people saying that you must use the 'reserved word prefix' and simply put an uderscore in front of the attribute like so:

<%= Html.CheckBoxFor(model => model.SeatOnly, new { _checked = "checked" })%>

This does not generate an error but in the generated html the attribute is actually '_checked' which means it doesn't work (if I use firebug and remove the underscore the attribute then takes effect).

Does anyone know a way around this while still using CheckBoxFor?

Thanks

like image 304
jcvandan Avatar asked Apr 22 '10 08:04

jcvandan


2 Answers

<%= Html.CheckBoxFor(model => model.SeatOnly, new { @checked = "checked" })%>

You need to prefix it with an '@' :-)

Update

Just tested with the following and works. Try this ...

Model

public class MyModel
{
    public bool SomeBooleanValue { get; set; }
    public string Title { get; set; }
}

View (snipped to only the important bits)

<%= Html.TextBoxFor(x => x.Title) %>

<%= Html.CheckBoxFor(x => x.SomeBooleanValue, new { @checked = "checked" }) %>
like image 94
WestDiscGolf Avatar answered Nov 13 '22 22:11

WestDiscGolf


I had the same problem: the "checked" attribute was always omitted in the html code. i solved the problem by passing "true" into the model. snippet looks like this:

MyModel model = new MyModel();
model.SomeBooleanValue = true;

As you connect the Checkbox with the Model the checkbox always shows the value the model has. If the value in your model is "false" the checkbox will always be unchecked.

Maybe this helps ..

like image 24
mikoku Avatar answered Nov 13 '22 20:11

mikoku