Home > database >  How do you pass perameter from a view to a controller function using ajax
How do you pass perameter from a view to a controller function using ajax

Time:09-28

I have a view with a button to call ajax but now need to include a parameter new { DNumber = item.DrawingNumber } and have that passed into the controller via ajax. What do I need to add to my code to make this work please?

view: PDF

<script>
    function OpenDrawingPDF() {
     $.ajax({
              url: "OpenDrawingPDF",
              success: function () { alert("success"); } 
            });
       return false;
    } 
</script>

Controller:

public void OpenDrawingPDF(string DNumber)
{
    string Path = @"\\Serv1\Company\10 - Production\Production Drawings\CAD pdf\";

    if (Directory.Exists(Path))
    {
        string Folder = DNumber.Substring(4, 2)   @"\";

        System.Diagnostics.Process.Start(Path   Folder   DNumber   ".pdf");
    }
}

CodePudding user response:

Check the following approach. Provide your Id to your element holding a DBNumber and then access it from your function:

var dbNumber = $('#dbNumberItemId').val();
$.ajax({
    url: "OpenDrawingPDF",
    type: "Get", // I assume that you are sending get request
    data: { 
        dbNumber: dbNumber
    },
    ...
 });

CodePudding user response:

This was the solution that worked for me:

view:

<a id="myid" [email protected] href="javascript:" onclick="myPDF('tblCircuitDiagrams', this)">PDF</a>

<script>
    function myPDF(table, value) {

        var mydata = document.querySelector('#myid');

        var dbNumber = value.dataset.mydata1;

        $.ajax({
            url: "OpenDrawingPDF",
            data: { DNumber : dbNumber },
            cache: false,
            type: "GET"
        });
    }
</script>

controller:

public void OpenDrawingPDF(string DNumber)
{
    string Path = @"\\serv1\Company\10 - Production\Production Drawings\CAD pdf\";

    if (DNumber != null && Directory.Exists(Path))
    {
        string Folder = DNumber.Substring(4, 2)   @"\";

        System.Diagnostics.Process.Start(Path   Folder   DNumber   ".pdf");
    }

}
  • Related