Shariq Ali
Shariq Ali

Reputation: 33

How to show checkbox checked/unchecked on the basis of bool variable fetched from database

I am new to ASP MVC development. I wanted to ask that how can i set the check box value to true or false based on the bool variable result? I have tried using the following approach:

     @Html.CheckBoxFor(f => f.SFLandRFListAttached, new {Value = @ViewBag.formfetched.SFLandRFLListAttached})

Like here "@ViewBag.formfetched.SFLandRFLListAttached" returns a bool value, but it doesn't check/uncheck the checkbox. Please help I am new to MVC coding.

Upvotes: 0

Views: 516

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You just need to set the Model/ViewModel property to the value which the variable hold in the controller and the strongly typed helper method will take care and will decide either to check the checkbox or not depending on the value in it.

In controller action set the property value on the basis of whatever your business logic is and pass the model from controller to view.

Your controller would have logic to set the property like:

model.SFLandRFListAttached = SomeMethodReturningBoolean();
return View(model);

then you just need to write following in View:

@Html.CheckBoxFor(f => f.SFLandRFListAttached) 

Hope it helps!

Upvotes: 1

Related Questions