为什么查询字符串参数包含两次 - asp.net boolean

时间:2012-12-25 05:40:43

标签: c# asp.net-mvc viewmodel strongly-typed-view

我的索引页面包含以下代码:

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

我的模特是:

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();

浏览到该页面然后选择IncludeArchive复选框以将其设置为true时,查询字符串将变为

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

为什么它在查询字符串中包含变量IncludeArchive两次?

由于

1 个答案:

答案 0 :(得分:2)

这是MVC使用复选框的方式。如果您浏览页面的HTML,您会注意到对于使用HTML帮助程序呈现的每个复选框,您都有一个带有false值的隐藏字段。这可确保在用户未选中您的复选框时发送错误值。这就是为什么如果你选择一个复选框你有两个值,如果你没有选择它只有一个值。有关详细信息,您还可以查看此帖子: 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?

希望它有所帮助。