如何从WebForm中的Jquery Ajax调用c#方法?

时间:2017-04-17 14:04:54

标签: javascript c# jquery asp.net ajax

我是编码的新手,我试图通过jquery ajax调用我的c#方法,因为我的表单操作不允许我的OnClick()事件运行,我无法删除表单操作因为,我的表单来自专有软件和每次都自动给出表单操作,我试图再次将其更改为默认值,但这不起作用。所以现在我试图通过Jquery Ajax运行我的C#代码。如果你有更好的解决方法,请建议。 感谢您的帮助,谢谢您提前

<%@ 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>

代码背后:

 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;
        }
    }



}

}

1 个答案:

答案 0 :(得分:0)

您将实现Web服务,或者您将使用处理程序文件。通常使用此通用处理程序,因为它不需要表单。使用模板后,您将拥有一个应如下所示的文件:

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

     }

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

从您的主要应用程序或表单中,您将按如下方式执行ajax:

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

这是最简单的方法之一。因为它允许您分离您的逻辑,与您在[WebMethod]属性中修饰的代码中的方法声明相比。