Pass in @(Model.newsletterOptin ? true : false) value into checked key inside a dictionary for htmlhelper

93 Views Asked by At

I am trying to replace some html with html helpers and I am trying to pass a dictionary of HTMLAttributes into the CheckboxFor helper method. My problem is that I do not know how to get this expression to work as an object param for my instantiation of the dictionary for the id checked. The html looks like this

<input type="checkbox"
    id="newsletterOptin"
    name="newsletterOptin" 
    checked="@(Model.newsletterOptin ? true : false)" />

and the helper looks like this

@Html.CheckBoxFor(m => m.newsletterOptin, new Dictionary<string, object>() {
    { "id", "newsletterOptin" },
    { "checked", "@(Model.newsletterOptin ? true : false)" }
})

How can I pass the @(Model.newsletterOptin ? true : false) so that it is used properly?

1

There are 1 best solutions below

0
On

Your helper starts with an @ sign, which starts a code block in ASP.NET Razor. You don't need to use @ again, because you can write it like any other plain C# code:

@Html.CheckBoxFor(m => m.newsletterOptin, new Dictionary<string, object> { 
    { "id", "newsletterOptin" },
    { "checked", Model.newsletterOptin ? "true" : "false" }
})