我的索引页面包含以下代码:
<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 复选框以启用它时,查询字符串变为
http://localhost:64005/test/?FirstName=&LastName=&TestNumber=&IncludeArchive=true&IncludeArchive=false
为什么在查询字符串中两次包含变量IncludeArchive?
谢谢
最佳答案
这是 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?
希望对您有所帮助。
关于c# - 为什么查询字符串参数包含两次 - asp.net boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028020/