I'm trying to pass a list (array) of radio buttons from JavaScript to a C# Net Core 6 controller.
HTML is like this:
<input class="js-filter-item" type="radio" name="Performance_Type" value="Standard" id="filter-group-Performance_Type--item-Standard" /> <input class="js-filter-item" type="radio" name="Performance_Type" value="VIP" id="filter-group-Performance_Type--item-VIP" /> <input class="js-filter-item" type="radio" name="Price" value="Up_to_£55" id="filter-group-Price--item-Up_to_£55" /> <input class="js-filter-item" type="radio" name="Price" value="Up_to_£70" id="filter-group-Price--item-Up_to_£70" />
So, there are many groups (more than I can show here), each with many options. I want to get the complete list of options with "name", "value" and "checked". Or, if simpler, just some "checked" options (using "id" will do)
The closest I've gotten so far is:
var options = document.querySelectorAll('.js-filter-item'); var optionsArray = JSON.stringify((Array.from(options).map(el => ([el.name, el.value, el.checked]))));
Parameters on the controller are defined as "strings"
However, I get this, which is not valid JSON:
[["Performance_Type","Standard",true],["Performance_Type","VIP",false]]
I feel like I didn't handle this the right way! Basically, in a C# controller, I need to know which options are checked.
Actually, this scenario can be implemented in many ways. In order to sort the selected radio buttons, first we should set the condition based on its Id. Furthermore, we need to bind these ids into classes and finally send the request to the controller.
Let's see it in practice: Suppose we have the following class.
model:
Controller:
Check:
HTML:
Note: I set the checked attribute in the first and last radio button to test the scenario. You have to do this in an if condition based on the Id or name attribute. There are tons of examples online on how to do this.
script:
Output: