I have a .cshtml view like it:
<form asp-controller="X" asp-action="Y">
@for (int i = 0; i < Model.SomeListOfStrings.Count; i )
{
<input type="checkbox" value="@Model.SomeListOfStrings[i]" />
}
<input type="submit" />
</form>
And I want to send value of this <input type="checkbox" value="@Model.SomeListOfStrings[i]" />
instead of boolean in my request (and only if checkbox is checked). How can I do it?
CodePudding user response:
You should be able to do something like this in your cshtml:
<form asp-controller="Home" asp-action="Index">
@for (int i = 0; i < Model.SomeListOfStrings.Count; i )
{
<input name="AreChecked" type="checkbox" value="@Model.SomeListOfStrings[i]" /> @Model.SomeListOfStrings[i]
<br />
}
<input type="submit" />
</form>
Give your input's the same name - AreChecked
in this example. Set the value
to your strings in your collection as you are already.
Then, in your controller method, add a List<string>
parameter called AreChecked
or whatever you named it, and that should automatically bind the checked items and have their values upon submitting:
[HttpPost]
public IActionResult Index(List<string> AreChecked)
{
return Ok();
}
Example view:
If I check the "hi" and "hello" checkboxes, when I submit the form, the controller's parameter is bound with those values:
I referenced this page to do this if you want more information.