1

I am new to the coding and i am trying to call my c# method through jquery ajax because my form action is not allowing my OnClick() event to run, I cannot remove form action because, my form comes from proprietary software and gives form action automatically every time, i tried to change it to default again but that doesn't work. So now I am trying to run my C# code through Jquery Ajax. If you have better way to solve it please suggest. Your help is appreciated, Thank You in advance

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HTMLtoPDF.aspx.cs" 
Inherits="HTMLtoPDF.HTMLtoPDF" %>

<!DOCTYPE html>
<!--[if IE 9]><html class="lt-ie10" lang="en" > <![endif]-->
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Incomplete Grade Application</title>

</head>
<body>
   <form action="xyz.aspx" id="form1" runat="server"  method="post" name="form1">


  /// Web Form ///



        <div class="row">
            <div class="col-sm-12">
                <label class="control-label" style="margin-top:0px;margin-left:20px">Please use your mouse/finger sign below:</label>
                <div id="esignature"></div>
                <input type="hidden" id="bitmap" name="bitmap" value="" />
            </div>
        </div>
        <div class="row">
            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
                <button type="button" class="btn btn-danger btn-xs" id="clear">Clear Signature</button>
            </div>
            <div class="col-lg-2 col-lg-offset-6 col-md-2 col-md-offset-6 col-sm-2 col-sm-offset-6 col-xs-2 col-xs-offset-6">
                <div class="pull-right">
                    <input type="submit" class="btn btn-danger" id="reject-button" name="button" value="Reject" />

                </div>

            </div>
            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">

                <input type="button" ID="submit"  class="btn btn-success" value="Approve" />

               <button id="hiddenButton" runat="server" onserverclick="btnClick_Click" style="display:none;" ></button>

            </div>

        </div>

        <hr style="background-color:#750D17;height:1px" />

        <div class="row">
            <div class="col-lg-12">
                <input type="text1" class="form-control" id="reject-reason" name="reject-reason">

                <p class="help-block">Reject Reasons (if rejected)</p>
            </div>


        </div>





    </div>
</div>
<br />
<br />

</form>


    <script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-migrate-1.3.0.js"></script>
<script src="https://workflow.stratford.edu/Content/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>

<!--[if lt IE 9]>
<script src='https://workflow.stratford.edu/Content/jSignature/flashcanvas.js' type='text/javascript'></script>
<![endif]-->
<script src='https://workflow.stratford.edu/Content/jSignature/jSignature.min.js'></script>
<script type="text/javascript">

    var isEmpty = function (element) {
        if ($("#" + element).val() == "" || $("#" + element).val() == null) {
            return true;
        } else {
            return false;
        }

    };

    var arrayCheck = function (array) {
        for (var i = 0; i < array.length; i++) {
            if (array[i] == false) {
                return false;
            }

        };

        return true;
    };

    function arrayAssign(array, num) {
        for (var i = 0; i < num; i++) {
            array[i] = false;

        };

        return array;
    };



    function validationCheck(array, number, element) {
        if (isEmpty(element)) {
            $("#" + element).parent(".form-group").addClass("has-error");
            array[number] = false;
        } else {
            $("#" + element).parent(".form-group").removeClass("has-error");
            array[number] = true;
        }
    };

    var pass1 = [];





    $(document).ready(function () {
        if ($.browser.msie) {
            if (parseInt($.browser.version) < "9.0") {
                alert("Sorry! This form does not support your current IE version, please use Firefox/Google Chrome to submit.");
            }
        }

        var preSig = $('#stu-sig-bit').val();
        $('#stu-sig').attr('src', preSig);
        var fakeVari = $("#typea").val();

        $("#esignature").jSignature({
            "background-color": "transparent",
            "decor-color": "transparent",
            "color": "#1489FF",
        });

        $("#clear").click(function () {
            $("#esignature").jSignature("reset");
        });



        $("input[type=text]").attr("readonly", true);
        $("textarea1").attr("readonly", true);
        //$("input[type=radio]").attr("disabled", "disabled");
        $("#reject-reason").attr("readonly", false);




        $("#submit").click(function () {


            $("#bitmap").val($("#esignature").jSignature("getData"));

            arrayAssign(pass1, 2);
            pass1[2] = false;

            validationCheck(pass1, 0, "remaining_work");
            validationCheck(pass1, 1, "deadline_date");


            pass1[2] = true;

            if (!arrayCheck(pass1)) {
                return false;
            }
            else if ($("#esignature").jSignature("getData", "native").length == 0) {
                alert("Please sign at bottom of the form.");
                return false;
            } else {
                $("#iso_sig").val($("#bitmap").val());
                $("#iso_decision").val("no");
                var date = new Date();
                var month = date.getMonth() + 1;
                var day = date.getDate();
                var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
                $("#iso_date").val(temp);

                var answer = confirm('Are you sure you want to approve the case?');
                if (answer == true) {

                    document.getElementById('<%= hiddenButton.ClientID %>').click();


                } else {
                    return false;
                }

            }



        });


        $("#reject-button").click(function () {


            $("#bitmap").val($("#esignature").jSignature("getData"));
            if (isEmpty("reject-reason")) {
                alert("Please write down the reason why you reject the request.");
                return false;
            } else if ($("#esignature").jSignature("getData", "native").length == 0) {
                alert("Please sign at bottom of the form.");
                return false;
            } else {
                $("#iso_sig").val($("#bitmap").val());
                $("#iso_decision").val("no");
                var date = new Date();
                var month = date.getMonth() + 1;
                var day = date.getDate();
                var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
                $("#iso_date").val(temp);

                var answer = confirm('Are you sure you want to reject the case?');
                if (answer == true) {

                } else {
                    return false;
                }

            }



        });



    });
</script>

Code Behind:

 protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnClick_Click(object sender, EventArgs e)
    {

        DownloadAsPDF();
    }

    public void DownloadAsPDF()
    {
        try
        {
            string strHtml = string.Empty;
            string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "CASEID6.pdf";
            //string testPath = Server.MapPath("~/files/test.pdf");

            string template = File.ReadAllText(Server.MapPath("~/Incomplete-Pdf-temp.html"));


            CreatePDFFromHTMLFile(template, pdfFileName);

            Response.Redirect("SendEmail.aspx");




        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }



    public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
    {
        try
        {
            object TargetFile = FileName;

            string ModifiedFileName = string.Empty;
            string FinalFileName = string.Empty;




            GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
            GeneratePDF.HtmlPdfPage first = builder.AddPage();
            first.AppendHtml(HtmlStream);
            byte[] file = builder.RenderPdf();
            File.WriteAllBytes(TargetFile.ToString(), file);

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
            ModifiedFileName = TargetFile.ToString();
            ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");

            iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
            reader.Close();
            if (File.Exists(TargetFile.ToString()))
                File.Delete(TargetFile.ToString());
            FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
            File.Copy(ModifiedFileName, FinalFileName);
            if (File.Exists(ModifiedFileName))
                File.Delete(ModifiedFileName);

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }



}

}

Naive
  • 345
  • 2
  • 6
  • 18
  • refer [link](http://stackoverflow.com/questions/4508409/ajax-method-call) – Dhaval Pankhaniya Apr 18 '17 at 06:53
  • @Dhaval will it work because the method in C# file is void and it need static, cause i tried the example given in that link but it only gives alert message of success but doesn't call the method. – Naive Apr 18 '17 at 13:23

1 Answers1

0

You would implement a web-service, or you would utilize a handler file. This generic handler is often used, since it doesn't require a form. Once you utilize the template you'll have a file that should appear as follows:

public class SampleHandler : IHttpHandler
{
     public void ProcessRequest(HttpContext context)
     {

     }

     public bool IsReusable
     {
          get { return false; }
     }
}

From your primary application, or form, you would execute your ajax as follows:

<script type="text/javascript">
     $.ajax({
         url: '<% Page.ResolveUrl("/SampleHandler.ashx") %>',
         method: 'post', 
         ...,
         success : function (response) {
              // Handle .ashx response.
         }
     });
</script>

That is one of the simplest approaches. As it will allow you to separate your logic, compared to the declaration of a method in your code behind decorated in a [WebMethod] attribute.

Greg
  • 11,302
  • 2
  • 48
  • 79
  • I created handler as you told, but i don't know where can shall i put my c# code ? – Naive Apr 17 '17 at 19:55
  • @Naive Your C# code would go inside the process request, and you would return it via the current `HttpContext` and you can access particular data through the `HttpContext`. – Greg Apr 17 '17 at 19:57
  • Can i directly call C# code with jquery ajax ? $.ajax({ url: '<% Url("page1.aspx/HTMLtoPDF") %>', method: 'post', success : function (response) { alert("success"); } }); – Naive Apr 17 '17 at 20:13
  • @Naive Well, you could hit that .aspx page, then have the page load return content by `HttpContext.Response.End();` but that really isn't the correct way. You really should abstract outward, and use a service to handle that functionality for you automatically. – Greg Apr 17 '17 at 20:20
  • thank you, right now i am trying to implement through handler as you said, will let you know what the output is, but i really appreciate your help. – Naive Apr 17 '17 at 20:25
  • I did as you said, i just kept alert box in success, it gives me alert message but doesn't run the code in background which is to convert pdf and redirect the page by sending email. – Naive Apr 17 '17 at 20:45
  • I'm preoccupied at the moment, it does work. I've done it on several sites. I'll see if I can help you later when I have more time. – Greg Apr 17 '17 at 21:28