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...

2
  • 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) Commented Jan 14, 2016 at 1: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 <input type="checkbox" /> whereas <input type="checkbox" checked="false"/> will tick the box as will <input type="checkbox" checked="anything-you-like"/> If the checked attribute exists, it will be checked regardless of the value. Commented Jan 14, 2016 at 1:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

it's possible that <input type = "checkbox" checked = "true or false?" pass the checked value to a controller?
Thank you so much @BhavikPatel for this well detailed answer! Helped me out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.