簡體   English   中英

如何從WebForm中的Jquery Ajax調用c#方法?

[英]How can I call c# method from Jquery Ajax in WebForm?

我是編碼的新手,我試圖通過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;
        }
    }



}

}

您將實現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]屬性中修飾的代碼中的方法聲明相比。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM