Reputation: 9
How do I pass a value from my checkbox (view) to the controller?
<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>
My controller:
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)
{
///????
}
I dont know what to put in the view and controller to pass the values.
Upvotes: 0
Views: 306
Reputation: 9463
You should introduce a ViewModel. A simple way to send the values is to POST this ViewModel to your controller action.
public class FilterViewModel {
[DisplayName("Apple")]
public bool DoApplyAppleFilter { get; set; }
}
Tell the View Filter.cshtml
to use this 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>
}
Controller Action:
[HttpPost]
public IActionResult Filter(FilterViewModel viewModel) {
bool isChecked = viewModel.DoApplyAppleFilter;
// ...
}
Instead of a submit <button>
, you can also use AJAX to POST the <form>
, or extract the values and use a GET request.
Upvotes: 2