Hi @Anjali Agarwal
To display check box list using ViewData, you can refer to the following sample code:
View page:
<div class="form-group">
Select Test: <br />
@{
var select = ViewData["testing"] as SelectList;
if (select !=null && select.ToList().Count>0)
{
foreach (var item in select.ToList())
{
<input type="checkbox" name="selectedItems" value="@item.Value" @(Html.Raw(item.Selected ? "checked=\"checked\"" : "")) /> @item.Text <br/>
}
}
}
</div>
Controller: use a string array to receive the checkboxlist selected values:
private List<SelectListItem> test()
{
return new()
{
new SelectListItem() { Text = "test1", Value = "1" },
new SelectListItem() { Text = "test2", Value = "2" },
new SelectListItem() { Text = "None", Value = "3" },
new SelectListItem() { Text = "test3", Value = "4" },
};
}
public IActionResult Index()
{
ViewData["testing"] = new SelectList(test(), "Value", "Text");
return View();
}
[HttpPost]
public IActionResult Index(string[] selectedItems) //use a string array to receive the checkboxlist selected items (selected value.)
{
return View();
}
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion