Home > Mobile >  ASP.NET Core MVC Radio button on change event call controller action
ASP.NET Core MVC Radio button on change event call controller action

Time:12-09

I have a simple two radio buttons in my ASP.NET Core MVC app, by default A1 radio button is selected and it calls A1 (controller and action).

I made a change in code to call A2 controller Index action (HttpPost), but it isn't working

Index.cshtml:

 <div >
        <input  onclick="'getA1Rates()'" type="radio" name="flexRadioDefault" id="flexRadioA1" checked />
        <label  for="flexRadioDefaultA1"> A1 </label>
    </div>
    <div >
        <input  onclick="'getA2Rates()'" type="radio" name="flexRadioDefault" id="flexRadioA2" />
        <label  for="flexRadioDefaultA2"> A2 </label>
    </div>

.cshtml javascript code:

<script type="text/javascript">
    function getA1Rates() {
        $.ajax({
            type: "POST",
            URL: "/CodesController/Index/",
            data: { id: $('#flexRadioA1').val() },
            dataType: "json",
            success: function (result) {
                alert("success")
            },
            error: function () {
                alert("failed");
            }
        });
    }
    function getA2Rates() {
        $.ajax({
            type: "POST",
            URL: "/CodesController/Index/",
            data: { id: $('#flexRadioA2').val() },
            dataType: "json",
            success: function (result) {
                alert("success")
            },
            error: function () {
                alert("failed");
            }
        });
    }
</script>

My CodesController:

 public async Task<IActionResult> Index()
 {
     // blah..blah..
 }

 [HttpPost]
 public async Task<IActionResult> Index(string data)
 {
     // blah..blah..
 }

My browser console also looks good I don't see any $ undefined error or so

CodePudding user response:

Can you use this way : enter image description here

  • Related