views:

67

answers:

3

Hello all, this is a follow-up to the question I posted yesterday. I was able to get the checkboxes implemented correctly, thank to all your suggestions. Now I'm trying to tackle the second issue which is maintaining the checkbox state during a page refresh or when a user clicks the back button on there browser. Again I have the following sample code in my view:

   <tr>
   <td><label for="Name">Name</label></td>
   <td><%= Html.Encode(entity.CONTACT_NAME)%></td>
   <td><%= Html.CheckBox("Name", false, new {@value = Html.Encode(entity.CONTACT_NAME)}) %></td>
   </tr>

When I check the box, I get the following value for the Name key in the ModelState "John Doe, false". From what I understand, the checkbox html helper gets its value from the ModelState. But when the page re-renders and gets to this particular line of code, I get the following error:

The parameter conversion from type 'System.String' to type 'System.Boolean' failed

Again, my goal is to simply maintain the checkbox state, not sure what is going on here.

UPDATE:

If the checkbox gets the value from the ModelState when re-rendering and if the keys are stored as strings, how do I convert them to boolean values?

+1  A: 

Your trying to set the value of the checkbox to the entity's contact name, which i guess is a string?

You'll need to set the value to a boolean property of entity.

Fermin
A: 

Make sure the property or expression you are using to set the value of the checkbox is a boolean type.

Dan
I understand that, but if the boolean values are past as string literals in the initials POST, i.e. "true, false", or in my case "Name, false", how am I supposed to convert them back to boolean?? I can change string Name to "true", but it's still a string.
kingrichard2005
A: 

Was able to resolve it, thanks for all your suggestions. In my case I had to pass the ModelState as a parameter in a method that looked through all values in the ModelState that weren't just false and set them to true by calling the SetModelValue.

Example:

errorHandler(ModelStateDictionary modelState, ChangeRequest aChangeRequest)
{
               if (aChangeRequest.Job != "false")
                modelState.SetModelValue("Job", new ValueProviderResult("true", "true", new CultureInfo("en-US")));

  //Etc.
}

For this project, I created a class object that was populated with values using TryUpdateModel in my controller and then passed this into the method as well. I'm sure there's a much more efficient way, but this seems to work, any additional suggestions are welcome.

kingrichard2005