Ad

How To Get The Value Of A Radio Button In Razor To Pass It As A Parameter To An Action?

- 1 answer

In a view I have two radio buttons:

 @Html.RadioButtonFor(model => model.TipoVP, new String("VP_A".ToCharArray()), new { @checked = "checked" })
 <span class="custom-control-label">Partial View A</span>
 @Html.RadioButtonFor(model => model.TipoVP, new String("VP_B".ToCharArray()))
 <span class="custom-control-label">Partial View B</span>  

Action of the controller is like this:

 public ActionResult GetVistaParcial(string tipov)
 {
    if (tipov == null || tipov == "VP_A")
       return PartialView("_PartialView_A");
    else
       return PartialView("_PartialView_B");
 }

}

And a call to a controller action to load a partial view or another according to the selected radio button

 @Html.Action("GetVistaParcial", "miControlador", new { tipov = "the value of checked RadioButton" } )  

The script for the change event of radio button are:

 $("[name=TipoVP]").on('change', function () {
    var $rb = $(this);
    $.ajax({
       url: '/miControlador/GetVistaParcial/',
       data: { tipov: $rb.val() },
       success: function (respuesta) {
          $("#vistaparcial").html(respuesta);
       }
    });
 });

How can I pass the value of the radio button checked as a parameter to the action?
It must work when doing the GET and the POST

Ad

Answer

I am wondering if you want go to another page.

@using (Html.BeginForm("GetVistaParcial", "Home"))
{
  @Html.RadioButtonFor(model => model.TipoVP, new 
     string("VP_A".ToCharArray()), new { @checked = "checked" })
         <span class="custom-control-label">Partial View A</span>

  @Html.RadioButtonFor(model => model.TipoVP, new 
     String("VP_B".ToCharArray()))
       <span class="custom-control-label">Partial View B</span> 

  <input type="submit" value="submit" />
}

and you don't need to call this:

@Html.Action("GetVistaParcial", "miControlador", new { tipov = "the value of checked RadioButton" } ) 

Your Action should receive the model:

public IActionResult GetVistaParcial(YourModel model)
{
   return View();
}
Ad
source: stackoverflow.com
Ad