Sam
Sam

Reputation: 25

How to send a parameter to the controller?

To send a parameter to a controller I use this :

<a class="btn btn-primary " @Html.ActionLink("Valider", "Create", new { iddemande = item.demandelist.id_demande   })></a>

To open a popup I use this:

   <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data- target="#exampleModalCenter" iddemande=item.demandelist.id_demande )>
               ADD
            </button>
            <!-- Modal -->
            <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-url=" @Url.Action("Create","valideyds")">

My question is how do I send the parameter to the controller that opens the popup through a button?

I explain I want at the same time to send the parameter iddemande = item.demandelist.id_demande and open the popup with the same button.

Thanks for your help

Upvotes: 1

Views: 420

Answers (1)

Jerdine Sabio
Jerdine Sabio

Reputation: 6140

You need to use ajax, this will send a request to a controller action asynchronously (without the need of redirect) at the same time you could open the modal based on the result.

First add a class to your button, I used modal-button and use data-property for assigning the value you want to pass. I used data-id;

<button type="button" class="btn btn-primary btn-sm modal-button" data-toggle="modal" data- target="#exampleModalCenter" data-id="@item.demandelist.id_demande">
   ADD
</button>

Add this to your @section scripts, in here we want to attach an event to the modal-button and get data-id and pass it to the controller via ajax.

<script>
   $(document).ready(function(){
      $(".modal-button").click(function(){
         // get data-id
         var id = $(this).data("id");

         // pass the id to controller
         $.ajax({
            type: "GET",
            url: "/ControllerName/ActionName",
            data: {iddemande:id},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(result){
               alert(result);
            },
            error: function(err){
               alert(err);
            }
         });
      });
   });
</script>

Upvotes: 1

Related Questions