tags:

views:

76

answers:

2

Hello, I've been working on an ASP.net MVC project that uses checkbox HTML Helpers in one of the views. The problem I'm trying to resolve is maintaining the checkbox state on a page refresh or when a user hits to he back button on their browser. I'm trying to use the HTML helper as a start, but I lack a complete understanding of how it works. I'm stuck on the third parameter that asks for HTML attributes. A snippet from a form that I have is as follows:

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

To avoid confusion, I have an object called entity that I declare before my form, that has several string values, one of which is CONTACT_NAME. I have a separate, standard, html checkbox right above the HTML Helper for testing purposes. When my form POSTs, I get the value if I select the standard checkbox, if I select the helper I get only true.

  • What I want to know is, how I can get the value like I do when I select the standard checkbox?
  • And how can I maintain the checkbox state on page refresh??

Any help is appreciated, thanks.

UPDATE:

@NickLarsen - Looked at the HTML code that was generated, the value is "false"

Made changes as per anthonyv's and JonoW's suggestions, my View is now as follows:

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

But the generated HTMl still shows the value as a boolean "false" instead of the actual CONTACT_NAME.

As per NickLarsen's suggestion, here is the code in my controller that checks the values.

public ActionResult ProcessRequest(Request request, FormCollection form)
       {
            var aChangeRequest = new ChangeRequest();
            TryUpdateModel(aChangeRequest, new string[] { "Name" },form.ToValueProvider());
//Way more follows

}
+1  A: 

should "@name" be "@value"? It looks like you are trying to set the name twice...

I'm pretty sure you want to have the following:

<%= Html.CheckBox("Name", false, new {@value = Html.Encode(entity.CONTACT_NAME)}) %>
anthonyv
A: 

If you have 2 inputs with the same name, they will be posted as a list of values (which MVC is going to try convert to a boolean value). So it's probably going to distort your test by having 2 elements with the same name, would suggest changing one of the names.

JonoW