如何将复选框(视图)中的值传递给控制器?
<div className="row">
<div class="filters-container col-sm-3">
<h5 class="navbar navbar-dark bg-info">Brands</h5>
<p>Apple</p>
<input type="checkbox" class="filter" id="AppleFilter" value="true" name="Filters"></input>
</div>
</div>
我的控制器:
public class ProductController : DaoController<ProductDao, Product>
{
[HttpGet]
public override IActionResult Get()
{
return InnerGet();
}
[HttpGet("{value}")]
public IActionResult Search(string value)
{
var daoManager = HttpContext.RequestServices.GetService<DaoManager>();
List<Product> products = daoManager.ProductDao.SearchProduct(value);
return Ok(products);
}
[HttpGet]
public IActionResult Filter(string responsables, bool checkResp = false)
{
///????
}
我不知道要在视图和控制器中放置什么来传递值。
答案 0 :(得分:2)
您应该引入一个ViewModel。发送值的一种简单方法是将该ViewModel张贴到您的控制器操作中。
public class FilterViewModel {
[DisplayName("Apple")]
public bool DoApplyAppleFilter { get; set; }
}
告诉视图Filter.cshtml
使用此ViewModel:
@model FilterViewModel
@* this <form> will be posted to the "Filter" action in the "ProductController" *@
@using (Html.BeginForm("Filter", "Product", FormMethod.Post, new { @class = "ym-form"})) {
@Html.LabelFor(m => m.DoApplyAppleFilter) @* renders <label> with the given DisplayName for the checkbox *@
@Html.CheckBoxFor(m => m.DoApplyAppleFilter) @* renders <input type="checkbox"> *@
<button type="submit">Apply filter</button>
}
控制器操作:
[HttpPost]
public IActionResult Filter(FilterViewModel viewModel) {
bool isChecked = viewModel.DoApplyAppleFilter;
// ...
}
除了提交<button>
之外,您还可以使用AJAX来发布<form>
,或者提取值并使用GET请求。