[Solved] ASP.Net jQuery Ajax Error: Unknown WebMethod GetFile

RichardSa
 
on Nov 05, 2022 02:17 AM
544 Views

In one of my questions, Retrieve and display Word (DOCX) file from database in browser in ASP.Net using C# and VB.Net

I was trying to upload word document on to my webpage and after uploading and inserting the word file into my database, I tried to display the word file on another page but when it redirected to the next page, I got an error which came as a window pop-up.

Unknown WebMethod GetFile Parameter name: methodName

Default.aspx

<div class="container" id="centered">
    <div class="form-horizontal">
        <h1>Word Document</h1>
        <hr />
        <div class="vh-100 d-flex flex-column">
            <div class="hstack p-2 gap-2 bg-light">
                <input id="files" type="file" runat="server" class="form-control" accept=".docx" />
                <button id="loadButton" runat="server" type="button" class="btn btn-primary px-4">Load</button>
            </div>
            <div class="flex-grow-1 d-flex flex-row">
                <details class="docx-thumbnails h-100">
                    <summary></summary>
                    <div id="thumbnails-container" class="docx-thumbnails-container"></div>
                </details>
                <div id="document-container" class="overflow-auto flex-grow-1 h-100"></div>
            </div>
        </div>
        <asp:Button ID="buttonsend" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="#32657c" Font-Size="9pt" Text="Submit" OnClick="buttonsend_Click" />
        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    </div>
</div>

Home.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" intergrity="sha384-AYmEC3Yw5cVb3ZcuHt0A9w35dYTsvhLPVnYs9eStHfGJv0vKxVfELGroGkvsg+p" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous" />
    <script defer="" src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <link href='https://fonts.googleapis.com/css?family=Nunito' rel='stylesheet' />
     <link href="css/bootstrap.min.css" rel="stylesheet" media="all" />
    <link href="css/bootstrap.css" rel="stylesheet" media="all" />
    <title>Word Document</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="script" runat="server"></asp:ScriptManager>
        <div class="wrapper">
            <nav id="sidebar">
                <ul class="nav navbar-nav list-unstyled components">
                    <li>
                        <a href="certificatepdoc.aspx">
                            <i class="fad fa-file-certificate" aria-hidden="true"></i>navigation</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="idcardpdoc.aspx"><i class="fad fa-id-badge" aria-hidden="true"></i>navigation</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="gatepass.aspx">
                            <i class="fad fa-ticket" aria-hidden="true"></i>navigation</a>
                    </li>
                </ul>
                <ul class="list-unstyled components">
                    <li class="nav-item" id="Li2" runat="server"><a href="accountsettings.aspx">
                        <i class="fad fa-cog" aria-hidden="true"></i>Settings</a>
                    </li>
                </ul>
            </nav>
            <div id="content">
                <br />
                <hr />
                <asp:Label ID="labelid" runat="server" Text="uid"></asp:Label><asp:Label ID="createby" runat="server" Text="createby"></asp:Label><asp:Label ID="role" runat="server" Text="role"></asp:Label>
                <div class="container" id="centered">
                    <div class="form-horizontal">
                        <asp:Button ID="btnPrinnt" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="#32657c" Font-Size="10pt" Text="Print Document" />
                        <asp:Panel ID="printpanel" runat="server">
                            <div class="contentt">
                                <div id="word-container"></div>
                            </div>
                        </asp:Panel>
                    </div>
                </div>
                <br />
            </div>
        </div>
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
    <script type="text/javascript" src="https://volodymyrbaydalka.github.io/docxjs/dist/docx-preview.js"></script>
    <script src="js/bootstrap.min.js"></script>   
       <script type="text/javascript">
                    $(function () {
                        $.ajax({
                            type: "POST",
                            url: "Default.aspx/GetFile",
                            data: "{}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (response) {
                                var file = response.d;
                                PreviewWordDoc(file);
                            },
                            failure: function (response) {
                                alert(response.responseText);
                            },
                            error: function (response) {
                                alert(response.responseText);
                            }
                        });
                    });
 
                    function Base64ToBytes(base64) {
                        var s = window.atob(base64);
                        var bytes = new Uint8Array(s.length);
                        for (var i = 0; i < s.length; i++) {
                            bytes[i] = s.charCodeAt(i);
                        }
                        return bytes;
                    };
 
                    function PreviewWordDoc(file) {
                        //Convert Base64 to Byte Array.
                        varbytes = Base64ToBytes(file.Data);
 
                        //Convert Byte Array to File object.
                        vardoc = new File([bytes], file.Name);
 
                        //Set the Document options.
                        vardocxOptions = Object.assign(docx.defaultOptions, {
                            useMathMLPolyfill: true
                        });
                        //Reference the Container DIV.
                        varcontainer = document.querySelector("#word-container");
 
                        //Render the Word Document.
                        docx.renderAsync(doc, container, null, docxOptions);
                    }
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
 
            $("#sidebar").mCustomScrollbar({
                theme: "minimal"
            });
 
            $('#sidebarCollapse').on('click', function () {
                // open or close navbar
                $('#sidebar').toggleClass('active');
                // close dropdowns
                $('.collapse.in').toggleClass('in');
                // and also adjust aria-expanded attributes we use for the open/closed arrows
                // in our CSS
                $('a[aria-expanded=true]').attr('aria-expanded', 'false');
            });
 
        });
    </script>
</body>
</html>

Home.apspx.cs

In Home page where the word will be displayed, I made Ajax call to WebMethod and fetch the details from database based on the Session value.

Then I converted the binary data to base64 array and pass to the Ajax Success function.

After which I converted Base64 string to Byte Array and Byte Array to File object and finally, to display the Word Document using the JavaScript plugin.

But Its giving me error as stated above.

 

[WebMethod(EnableSession = true)]
public static object GetFile()
{
    string fileName = string.Empty;
    byte[] bytes = null;
    string type = string.Empty;
    using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security = True"))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM WordDocxTable WHERE Id = @Id", con))
        {
            cmd.Parameters.AddWithValue("@Id", HttpContext.Current.Session["invworddoc"]);
            con.Open();
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    fileName = dr["Name"].ToString();
                    bytes = (byte[])dr["Data"];
                    type = dr["ContentType"].ToString();
                }
            }
            con.Close();
        }
    }
    return new { Name = fileName, Data = Convert.ToBase64String(bytes), ContentType = type };
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 05, 2022 04:50 AM
RichardSa says:
url: "Default.aspx/GetFile",

Change Default page with Home page like below.

url: "Home.aspx/GetFile",

 

dharmendr
 
on Nov 07, 2022 06:19 AM
on Nov 07, 2022 11:27 PM
RichardSa says:
                    function PreviewWordDoc(file) {
                        //Convert Base64 to Byte Array.
                        varbytes = Base64ToBytes(file.Data);
 
                        //Convert Byte Array to File object.
                        vardoc = new File([bytes], file.Name);
 
                        //Set the Document options.
                        vardocxOptions = Object.assign(docx.defaultOptions, {
                            useMathMLPolyfill: true
                        });
                        //Reference the Container DIV.
                        varcontainer = document.querySelector("#word-container");
 
                        //Render the Word Document.
                        docx.renderAsync(doc, container, null, docxOptions);
                    }

Replace above with below code.

function PreviewWordDoc(file) {
    //Convert Base64 to Byte Array.
    var bytes = Base64ToBytes(file.Data);
 
    //Convert Byte Array to File object.
    var doc = new File([bytes], file.Name);
 
    //Set the Document options.
    var docxOptions = Object.assign(docx.defaultOptions, {
        useMathMLPolyfill: true
    });
    //Reference the Container DIV.
    var container = document.querySelector("#word-container");
 
    //Render the Word Document.
    docx.renderAsync(doc, container, null, docxOptions);
}