unable to call class method from webpart ascx file

Kim Tompkins asked on August 29, 2022 22:43

I am trying to call a method in the corresponding web part class using javascript. I am creating the variables at the top of the file so I think they should be in scope but I am getting a parameter doesn't exist error when calling the method. I know that I am getting the cookie values for the Lat and Long variables. can somebody tell me what I am missing? asp is new to me. the error is coming from this line var sites = <%= NearestSitesByLocation(Lat, Long) %>;

ERROR: Message: error CS0103: The name 'Lat' does not exist in the current context

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="NearestDonationCenters.ascx.cs" Inherits="_Custom_webParts_NearestDonationCenters" %>

<p id="drives">Drives</p>

<script>
 var Lat;
 var Long;

$(document).ready(
  function(){

    Lat = getCoord("Latitude");
    Long= getCoord("Longitude");
     var sites = <%= NearestSitesByLocation(Lat, Long) %>;
     var x = document.getElementById("drives");
      x.innerHTML = Long;


  });



    function getCoord(cname) {
        let name = cname + "=";
        let ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }

        return "";
    } 

</script>

Correct Answer

Dmitry Bastron answered on September 14, 2022 09:11

Hi Kim,

You are mixing JS and server-side code in one file, and your example simply wouldn't work.

When the page gets rendered:

  1. Web server first tries to execute this line <%= NearestSitesByLocation(Lat, Long) %>
  2. Then, after the page is rendered, JS is executed to pick up $(document).ready() event

You need to substitute it with Ajax call.

Please refer to this thread on Stackoverflow, I think it outlines pretty similar issue.

0 votesVote for this answer Unmark Correct answer

Recent Answers


Kim Tompkins answered on September 14, 2022 18:49

Thank you for this response. Ajax was exactly what I needed.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.