我正在使用ViewBag存储复选框的状态。它总是显示错误。当我删除value="isCurrentFilter"
时,当我选中复选框时,它显示为启用状态。
谁能指导我哪里出问题了?
请给我提意见。
控制者
Public async Task<IActionResult> Index(bool searchText, bool currentFilter, int? page)
{
int selectedPage = page ?? 1;
int bypassCount = (selectedPage - 1) * _pagingOptions.PageSize;
if (searchText != false)
{
page = 1;
}
else
{
searchText = currentFilter;
}
ViewBag.CurrentFilter = searchText;
}
Index.cshtml
<form asp-action="Index" method="get">
@{ bool isCurrentFilter = ViewBag.CurrentFilter; }
<input type="checkbox" asp-for="searchText" value="isCurrentFilter" class="form-control" />
<div class="col-md-12">
<button class="btn btn-primary" type="submit">Search</button>
</div>
</form>
<table class="table">
<thead>
<tr >
<th>Message Id</th>
<th>Status</th>
<th>Resent</th>
<th>Resent Date</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
@if (Model.Items.TotalItemCount > 0)
{
@foreach (var item in Model.Items.ToList())
{
<td>@Html.DisplayFor(modelItem => item.MessageId)</td>
<td>@Html.DisplayFor(modelItem => item.Status)</td>
<td>@Html.DisplayFor(modelItem => resentString)</td>
<td>@Html.DisplayFor(modelItem => resentDateString)</td>
<td>@Html.DisplayFor(modelItem => createdDateString)</td>
</tr>
}
}
</tbody>
</table>
</div>
使用ViewBag存储复选框的状态。它总是显示错误。
如果在浏览器中检查checkbox的源代码,您会发现它可能如下所示,并且checkbox的value属性是false
,因此false
即使您选中并提交表单,也始终会得到。
当我删除
value="@isCurrentFilter"
时,当我选中复选框时,它显示为启用状态。
如果没有为复选框明确设置value属性<input type="checkbox" asp-for="searchText" class="form-control"/>
,则value属性将为true
。
上面呈现的HTML还将包含该searchText
属性的两个字段(复选框和隐藏字段)。如果选中此复选框,则过帐值将为searchText=true&searchText=false
。模型绑定器将从值中正确提取true。否则它将是错误的。因此,正如您所说,删除value="@isCurrentFilter"
将起作用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句