Create an array of radio buttons and pass it to the Net Core controller
P粉590428357
P粉590428357 2024-02-26 09:49:09
0
1
403

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_&#xA3;55" id="filter-group-Price--item-Up_to_&#xA3;55"  />
<input class="js-filter-item" type="radio" name="Price" value="Up_to_&#xA3;70" id="filter-group-Price--item-Up_to_&#xA3;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.

P粉590428357
P粉590428357

reply all(1)
P粉627427202

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:

public class RadioButtonModel
    {
     
        public string Name { get; set; }
        public string Value { get; set; }
        public string Id { get; set; }
        public bool IsChecked { get; set; }
    }

Controller:

[HttpPost]
    public ActionResult PostRadioBUtton(List radioButtonModels)
    {
        return Ok(radioButtonModels);
    }

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:

@section scripts {
    
    
    
    }

Output:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!