How to call a content page function from MasterPage javascript RRS feed

  • Question

  • User-173333858 posted

    Hi, I have a function in a content page in asp.net/ C# project, that is called from 2 places. The 1st is a content page, which calls this function and executes succesfully. But the 2nd time, I am calling this function from the MasterPage, and it does not execute. It seems to not find the url. Is there something that needs to be added for the MasterPage?

    Thursday, September 10, 2020 6:51 PM

All replies

  • User-943250815 posted

    Is not clear if you are calling a function in .JS file or in <script> tag.
    Considering all your pages uses MasterPage and your function is in a JS file, there are 2 ways:
    a) Load JS file in header section of MasterPage, JS file will be loaded for any ContentPage;
    b) Put a ContentPlaceHolder in header section of MasterPage, then load JS file on ContentPage as needed

    Thursday, September 10, 2020 7:28 PM
  • User475983607 posted

    As always requested, share code that reproduces this issue.  Your description of the problem does not make sense because content and master pages do not exist in JavaScript. There's just the DOM.  It would be helpful if we knew what URL is not found.

    Thursday, September 10, 2020 7:34 PM
  • User-173333858 posted

    Am still learning asp.net/ C#. So, will try my best. I am calling a static web- method from javascript. I think the problem might be the session variable I am trying to access inside the web- method.

            [WebMethod(EnableSession = true)]
            public static void UnlockRecs()
                 String EMPLID = HttpContext.Current.Session["LoginEmplId"].ToString();


    Here EMPLID is always null. I am using HttpContext.Current. everywhere I am referencing Session["LoginEmplID"], but do not know why it is null. Can someone point out what might be wrong?

    Friday, September 11, 2020 1:33 AM
  • User475983607 posted

    Once set, session is available in every request.  Exposing IDs to JavaScript can be a security risk because the ID is in clear text.  Why do you need the EMPLID in JavaScript?   Can you explain the programming problem you are trying to solve?

    I recommend using ASP.NET Identity rather than building custom own security if that's what you're doing.

    Friday, September 11, 2020 12:15 PM
  • User-173333858 posted

    I will try to paste my code here. My project has a master page that contains the header for the App name, etc, that I incorporate on all other pages. It also has a logout LinkButton. On the other pages, there is an 'Exit' button. This 'Exit' button and the logout LinkButtton when clicked, should first call a function in code behind that calls a stored procedure to free up the records  and then close the app. The 'Exit' button seems to do this, but when clicked, the 'Logout' Linkbutton, which is on the masterpage does not seem to reach the code behind function.  Let me know what I am missing. Thanks!


        <form id="form1" runat="server">
                <asp:ContentPlaceHolder ID="HeaderPlaceHolder" runat="server">
                    <div class="container-fluid" style="background-color:lightgray; width:100%; height:auto">
                        <div class="row">
                            <div class="col-md-3" style="align-content:center; height:210px" >
                                <table class="table table-sm text-left" style="border:none">
                                    <tr style="border:none">
                                          <img src="Logo.png" alt="logo" class="img-fluid"/></td>  
                            <div class="col-md-6 text-center" style="vertical-align:middle; height:210px">
                                <h1 style="font-size: 2.7vw;color:black">Non-Adopted Alert Review Tool </h1>
                            <div class="col-md-3 row float-lg-right" style="height:210px;" id="myDiv" runat="server"  >
                                <table class="table table-sm text-left table-borderless table-responsive" id="logDetailsID" runat="server">
                                    <tr style="border:none">
                                        <td id="usernameLbl" style="color:black; font-size:small; font-weight:bold; border:none"><b>User Name : </b></td>
                                        <td colspan="2" id="username" style="color:black ; font-size:small"></td>
                                    <tr style="border:none">
                                        <td id="lastLogLbl" style="color:black; font-size:small; font-weight:bold; border:none"><b>Last Login :</b></td>
                                        <td colspan="2" id="lastlogin" style="color:black; font-size:small; border:none"></td>
                                    <tr style="border:none">
                                        <td colspan="3" style="border:none; text-align:right">
                                            <div class="row float-right" style="padding-right:1em; padding-bottom:0.5em; text-align:right">
                                                <asp:LinkButton ID="lnklogout"  runat="server" Text="Close EDEP" style="color:black; font-size:small" ClientIDMode="Static" OnClientClick="CloseEDEP()"  />                                           

                     <asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
             <asp:ContentPlaceHolder ID="MainContent" runat="server">


    <script type="text/javascript">
            function CloseEDEP() {
                    var employeeId = '<%= Session["LoginEmplId"] %>';
                    type: "POST",
                    url: "PharmAudit_Form.aspx/UnlockRecs",
                    contentType: 'application/json; charset=utf-8',
                     dataType: 'json',
                        async: true,
                         data: JSON.stringify({ EmplId: employeeId}),
                     error: function (XMLHttpRequest, textStatus, errorThrown) {
                        window.location.href = "./Logout.aspx";
                    success: function () {
                        var parsedResult = result.d;
                        if (parsedResult) {
                            if (parsedResult.error_code == "0") // no error 
                                this.display = none;
                            else if (parsedResult.error_code == "2") {
                                //window.location.href = "Logout.aspx?ErrorValue=" + "2";

    Code behind function is another page:

    [WebMethod(EnableSession = true)]
            public static void UnlockRecs(string EmplId)

                String EMPLID = EmplId;

                string constr = ConfigurationManager.ConnectionStrings["getconn_EDEP"].ToString();
                    // In a using statement, acquire the SqlConnection as a resource.        
                    using (SqlConnection con = new SqlConnection(constr))
                        using (SqlCommand command = new SqlCommand("dbo.spDeleteRphAuditScript", con))
                            using (SqlDataAdapter sda = new SqlDataAdapter(command))
                                command.Connection = con;
                                command.CommandType = CommandType.StoredProcedure;
                                command.Parameters.AddWithValue("@EmpId", EMPLID);

                                //open the db connection 

                catch (Exception ex)
                    System.Web.Services.WebService wsError = new System.Web.Services.WebService();
                    wsError.Context.Response.StatusCode = 500;

                    wsError.Context.Response.AppendHeader("error", ex.Message);

                //catch (System.Data.SqlClient.SqlException sqlException)
                //    Response.Write("<script>alert(sqlException.Message);</script>");


    Friday, September 11, 2020 1:43 PM
  • User475983607 posted

    The LinkButton causes an HTTP post which refreshes the pages.  Add the following to stop the post.

    function CloseEDEP(e) {


    Keep in mind, this will only work if jQuery is loaded before the script tag.  You did not share all the relevant code.  However, you can solves these issues yourself by simply using the browser's dev tools.  Dev tools shows the HTTP requests and coding errors. 

    As a code review, I recommend using the standard security APIs that come with ASP.NET rather than building your own.  Your current design has security vulnerabilities. 


    Friday, September 11, 2020 2:31 PM