I am using a 3rd party control for GIS map related functions.
I had the need to call a C# Method from within javascript. I chose to use PageMethods
like this:
PageMethods.getFeature(x,y)
Works like a charm as long as you convert your method to a [WebMethod]
In this method I am passing in the coordinates of the mouse and it returns me map features. That I will highlight on the map.
From researching I found that you cant directly access the UI from inside a [WebMethod] so I decided to set a session variable and postback. On postback if the session variables exist I would make the necessary UI changes.
My WebMethod
looks like this:
[WebMethod(EnableSession = true)]
public static void getFeature(float x, float y)
{...
some code in here.
}
Update This is my jQUery:
<script>
$(document).ready(function (e) {
$(".MyMap").click(function (e) {
var posX = $(this).position().left;
var posY = $(this).position().top;
PageMethods.getFeature(e.pageX-posX, e.pageY-posY);
});
});
</script>
How do I force a postback inside of a WebMethod
. Most of the ways I know to postback don't work.
Special Thanks to @BenRobinson for assisting me in the right direction. Here is what I came up with. I am posting this for other people who may make a similar mistake. The short answer is: **You Cant
My main issue was I was using a [WebMethod]
so my c# code could be called from jQuery
. This worked perfectly until I needed access to the UI. Well technically a 'WebMethod' is almost like calling a web service. You cant have a remote web service update the UI. What you can do is after your function in jQuery runs that calls the [WebMethod]
, is have it call a new page (window.location
). That location can call the original page (in my case Default.aspx). I passed parameters in the request field that I needed to send to the UI, and I basically put code in that if on load you see a particular request variable then do something... It worked like a charm.
Here's a rough example: In my jQuery page I did this (to navigate to a new page):
window.location.replace("ZoomAndCenter.aspx?x=" + (e.pageX - posX) + "&y=" + (e.pageY - posY))
Here is what my ZoomAndCenter.aspx looked like:
protected void Page_Load(object sender, EventArgs e)
{
int x = 0;
double y = 0;
x = Int32.Parse(Request["x"].ToString());
y = Double.Parse(Request["y"].ToString());
//Run some more code
Response.Redirect("Default.aspx?Param1=xxxx&Param2=xxxx");
//passed the params in the redirect.
}
Then in the Default.aspx
if(request["param1"] == "something")
{
//do something
}