开发者

Running a JS Method on load from code behind

I am trying to load the following JS method:

 <script type="text/javascript">
    function initialize(lon,lat) {
    var myLatlng = new google.maps.LatLng(lon,lan);
    var myOptions = {
    zoom: 14,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    var marker = new google.maps.Marker开发者_JAVA技巧({
    position: myLatlng, 
    map: map
    });   
    }
</script>

In my code behind in VB.NET I then want to load such as:

initialize(53.349803617967446, -6.260257065296173)

I need to load in code behind since I have to get the longtidude and latidude from DB.


An alternative to Chuck's suggestion - you could keep the function in the .aspx and write out those values directly into the Javascript using inline code, like the following:

initialize(<%=strLat%>, <%=strLon%>)

strLat and strLon would be defined as protected variables in your code-behind.

If you really want the whole function to be written out by the code-behind, look into the RegisterClientScriptBlock method.


It's not usually best practice to call Javascript functions directly from the code behind. The code behind is code that happens prior to the page's rendering.

What I would do is add two hidden literals to your page, latitude and longitude, and call your initialize function on the DOM ready event. The initialize function would retrieve the lat/long values from the created literals.

Here is a good resource to learn about the DOM ready event if you're not familiar.

Edit: If the above is not an option, you can "call" it from the code-behind in a rather roundabout way (This is almost functionally equivalent to my other solution).

<body runat="server">

Make your body tag look like that and then add this to the code-behind:

var javascriptFunction = string.format("javascript:initialize({0}, {1})", latValue, longValue);
Body.Attributes.Add("Onload", javascriptFunction);


You can use RegisterClientScriptBlock to insert Javascript into the page from the code-behind.

You would insert it inside whatever function you want to register it from, and format it like this:

ClientScriptManager.RegisterClientScriptBlock(typeof(this), "SomeKeyName", "initialize(" + lat + "," + long + ");", true);

where SomeKeyName is a unique key that prevents the script from being added more than once per postback.


If you must register both the function and the call from the code-behind, you would want to use ScriptManager.RegisterClientScriptBlock for the function, and ScriptManager.RegisterStartupScript for the call to the function. If the rendering of the function is not dependent upon anything from your server code, you would be better off not registering it from code, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜