I'm trying to print all the selected checkboxes in the [HttpPost]
action method. But, I'm always getting count as 0. Can someone suggest me where I'm doing wrong?
Below is my Category
model class.
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public bool CheckboxAnswer { get; set; }
}
Since this is sample program, I've used CategoryData
class like below to bind to checkbox list controls.
public class CategoryData
{
public CategoryData()
{
}
public List<Category> Categories
{
get
{
var categories = new List<Category>
{
new Category { CategoryId = 1, CategoryName = "Beverages", CheckboxAnswer = true },
new Category { CategoryId = 2, CategoryName = "Condiments", CheckboxAnswer = false },
new Category { CategoryId = 3, CategoryName = "Confections", CheckboxAnswer = true },
new Category { CategoryId = 4, CategoryName = "Dairy Products", CheckboxAnswer = false }
};
return categories;
}
}
}
Below is the View: GetSelectedCheckBoxes.cshtml
@model IEnumerable<Practice.MVC.Models.Category>
@{
ViewBag.Title = "Get Selected CheckBoxes";
}
<h1>@ViewBag.Title</h1>
<form asp-controller="Test" asp-action="GetSelectedCheckBoxes" method="post">
@foreach (var category in Model)
{
<input type="checkbox" asp-for="@category.CheckboxAnswer" />
<label asp-for="@category.CategoryId">@category.CategoryName</label>
<input type="hidden" asp-for="@category.CategoryId" />
<input type="hidden" asp-for="@category.CategoryName" />
}
<input type="submit" id="Submit" name="Submit" value="Submit" />
</form>
Below is the [HttpGet]
version of my Controller
action method.
public IActionResult GetSelectedCheckBoxes()
{
var categories = new CategoryData().Categories;
return View(categories);
}
Below is the [HttpPost]
version of my Controller
action method.
[HttpPost]
public IActionResult GetSelectedCheckBoxes(List<Category> categories)
{
string selectedCheckboxes = string.Empty;
string notSelectedCheckboxes = string.Empty;
foreach (var category in categories)
{
if (category.CheckboxAnswer)
selectedCheckboxes += category.CategoryName + ", ";
if (!category.CheckboxAnswer)
notSelectedCheckboxes += category.CategoryName + ", ";
}
return Content(selectedCheckboxes + " ------ " + notSelectedCheckboxes);
}
As you can see in the below screenshot, I'm not getting categories
as parameter