Search code examples
c#asp.net-mvcviewmodelstrongly-typed-view

Why does query string parameter get included twice - asp.net boolean


I've got my Index page with the following code:

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

my model is:

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 browsing to the page then choosing the IncludeArchive checkbox to enable it to true, the query string turns to

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

Why does it include the variable IncludeArchive in the query string twice?

Thanks


Solution

  • This is the way MVC works with checkboxes. If you browse the HTML of your page you will notice that for each checkbox rendered with an HTML helper you have a hidden field with false value. This makes sure that false value is sent in case a user doesn't select your checkbox. That is actually why you have two values if you select a checkbox and only one value if you don't select it. For more details you can check this posts also: asp.net mvc: why is Html.CheckBox generating an additional hidden input Why does the CheckBoxFor render an additional input tag, and how can I get the value using the FormCollection?

    Hope it helps.