This is a translation of the question Why does query string parameter get included twice asp.net boolean

I have a page with the following code:

<div class="editor-field"> @Html.CheckBoxFor(model => model.IncludeArchive) @Html.ValidationMessageFor(model => model.IncludeArchive) </div> 

Model class:

 public class SearchModel { public string FirstName { get; set; } public string LastName { get; set; } public string TestNumber { get; set; } public bool IncludeArchive { get; set; } } [Authorize] public ActionResult Index(SearchModel search) { var test= db.Test.AsQueryable(); if (Request.QueryString.Count > 0) { if (!search.IncludeArchive) test = test.Where(x => x.Status == "Active"); } else { test= test.Where(x => x.Status == "Active"); } ViewBag.testList = test.ToList(); 

When I open the page and then select the IncludeArchive checkbox, the address line changes to the following:

 http://localhost:64005/test/?FirstName=&LastName=&TestNumber=&IncludeArchive=true&IncludeArchive=false 

Explain why the IncludeArchive variable is included twice in the url?

1 answer 1

This is not a bug, this is the way in which the MVC framework works with checkboxes.

If you pay attention to the generated HTML markup, you will see that each checkbox is rendered as html with a hidden field with a value of false.

This ensures that when the form is submitted, the value false will be sent if the user does not check the checkbox.

Indeed, try the next experiment. Place such a checkbox <input type="checkbox" name="MyTestCheckboxValue"></input> on the form and see what value goes to the server if the checkbox is not checked. You will see that the checkbox value is not transmitted to the server at all.

A similar trick is also used in Ruby on Rails and MonoRail.

See also the following questions: