Background
I have a bool in a view model class. I have an if statement checking to see if the bool is true or false. If false I set the value to true and call a view. In the view I have button that when clicked updates and calls the view again. My problem is that the bool keeps being set to false when the view is loaded. I don’t know why this is happening. Is there a way to stop the bool from being changed?
Attempts
I’m aware MVC is stateless.
The view I’ve been given to work with is a .aspx view with the “value” attribute of the input tag already being used. So I’m unable to update the value of the Submit button.
<input type="submit" class="button" value="bvCalc" />
Question
In whatever way, I’m looking to persist the state of the bool. I don’t know how to do this and I’m unsure as to whether or not the best thing to do at this point would be to
- use a hidden field in the view
- build an HTML Helper Extension that will update the bool from true to false
- return the modified value with the model information being sent back to the controller so I can evaluate the data in the if statement.
The way values get from a view to controller is via
ModelBinding. If you are not familiar with how this works you might like to Google it to get a better understanding.As a quick example, lets say the action method in your controller that you want to pass the bool to looks like this:
and your ViewModel looks like this:
As long as your view has some kind of field (e.g. text box, checkbox, hidden field) with a name that exactly matches the property name (in this case ‘MyBool’) and a value that will convert to the property (in this example the string ‘True’ can map to to the boolean
truevalue) –ModelBindingwill be able to populatemodel.MyBoolwithtruein your controller action.If you use the built-in helper methods, you don’t need to worry about getting the correct name/value in your field element – MVC will do this for you
e.g.
@Html.HiddenFor(model => model.MyBool)will render HTML something like