Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Html.CheckBox and form submit issue

Crazy issue with submitting of values in Html.Checkbox in ASP.NET MVC RC

Some of the values are just not come to Request.Params

At my form I have this line inside the cycle:

<%=Html.CheckBox("cb" + p.Option.Id, p.Option.IsAllowed, new { value = 6 })%>

and it renders to next:

    <input checked="checked" id="cb17" name="cb17" type="checkbox" value="6" />
<input name="cb17" type="hidden" value="false" /> 

    <input checked="checked" id="cb18" name="cb18" type="checkbox" value="6" />
<input name="cb18" type="hidden" value="false" /> 

    <input id="cb19" name="cb19" type="checkbox" value="6" />
<input name="cb19" type="hidden" value="false" />

    <input id="cb20" name="cb20" type="checkbox" value="6" />
<input name="cb20" type="hidden" value="false" />

    <input checked="checked" id="cb21" name="cb21" type="checkbox" value="6" />
<input name="cb21" type="hidden" value="false" /> 

After submitting the Form I'm get something like:

Form.Params["cb17"] = {6, "false"}
Form.Params["cb18"] = {6, "false"}
Form.Params["cb19"] = {"false"}
Form.Params["cb20"] = {"6,false"}
Form.Params["cb21"] = {"false"}

In the request string Some of the params are displayed twice (normal situation) and some only ONE TIME (only value of hidden field). It seems that it doesn't rely on whether checkbox was checked or not, whether value has changed or so...

Does anybody faced with such a situation? How can I work around?

like image 787
Andriy Tkach Avatar asked Mar 18 '09 14:03

Andriy Tkach


1 Answers

   <% using(Html.BeginForm("Retrieve", "Home")) %>//Retrieve is the name of the action while Home is the name of the controller
       <% { %>
    <%foreach (var app in newApps)              { %>  
  <tr> 
       <td><%=Html.CheckBox(""+app.ApplicationId )%></td>      

   </tr>  
<%} %>
 <input type"submit"/>
<% } %>

and in your controller

 List<app>=newApps; //Database bind
 for(int i=0; i<app.Count;i++)
 {

    var checkbox=Request.Form[""+app[i].ApplicationId];
    if(checkbox!="false")// if not false then true,false is returned
 }

the reason you check for false because the Html Checkbox helper does some kind of freaky thing for value true

True returns as:

it makes the string read "true, false"

so you may have thought it was two values but its just one and means true

False returns as:

it makes the string read "false"
like image 117
TStamper Avatar answered Sep 25 '22 19:09

TStamper