1

How can i get Boolean value or the true or false from controller to a Checkbox in View using this:

@Html.CheckBox("condition", @ViewData["Condition"])

or

<input type = "checkbox" checked = "**true or false?**">

I have this in my Controller..

public ActionResult Member(string sortOrder, string filter, string searchString, int? page, **bool? condition = false**)

and in my view is like this

please help me for this...

tereško
  • 58,060
  • 25
  • 98
  • 150
  • 1
    It just needs to be `@Html.CheckBox("condition")` And the parameter needs to be `bool condition` (not `nullable`). If the value of `condition` is true, the checkbox will display as checked, otherwise it will be unchecked. But I recommend you use a view model and pass it to the view so you can use the strongly typed HtmlHelper - `@Html.CheckBoxFor(m => m.Condition)` –  Jan 14 '16 at 01:27
  • `checked` is bool attribute. It's mere existence ensures the input is checked. So you don't want to `checked=anything` if false because it shouldn't be there i.e. a non checked checkbox would be `` whereas `` will tick the box as will `` If the `checked` attribute exists, it will be checked regardless of the value. – rism Jan 14 '16 at 01:42

1 Answers1

2

update your controller

public ActionResult Member(string sortOrder, string filter, string searchString, int? page,bool condition)
{
    ViewData["Condition"] = condition;
    // code line 1
    // code line 2
       ... 
}

If you are looking for checkbox check/uncheck code for Razor view

@Html.EditorFor(x => x.condition)

Will generate:

<input id="condition" type="checkbox" value="true" name="condition" />
<input type="hidden" value="false" name="condition" />

How does it work:

If checkbox not checked, form submit only hidden (false) If checked, then form submit two fields (false and true) and MVC set true for bool property

<input id="condition" name="condition" type="checkbox" value="@ViewData["Condition"]" />

This will always send default value, if checked

reference : https://stackoverflow.com/a/14731571/2318852

Community
  • 1
  • 1
Bhavik Patel
  • 1,466
  • 1
  • 12
  • 28