I have a google map in a page (Using the Javascript API v3)
the map is loaded like this:
In the Default.aspx page:
(This is the div where I will load the map)
The scripts I am using:
<script src="http://maps.google.com/maps/api/js?sensor=false&" type="text/javascript </script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/MapScript.js"></script>
The MapScript.j file which contains the javascript code for loading the map and all the other thing I need (markers, animations, mouse events...)
In the MapScript.js I load the map with this script
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
The "MapScript.js" contains lots of function that i use in the map.
Untill now everything works fine the map is loaded and all the functions works correctly.
But what I want to do is this:
I put the map in an Update Panel.
In the code behind
at page load the MapPanel is not visible
protected void Page_Load(object sender, EventArgs e)
{
MapPanel.Visible = false;
}
the on the click of a button I do a partial post back on the update panel and change the visibility of the map to true.
But the problem is that after the partial postback, the map stops showing.
I tried to use RegisterStartupScript to register all 3 of the javascript sources I am using. (I put it in the PageLoad event)
string scr;
scr = "<script src='/Scripts/MapScript.js'></script>";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "key", scr, false);
But it did not work.
Any help is greatly appreciated. Hope I was clear enough.
Thanks a lot
You need to initialize the map after the partial post back of your updatepanel like this.
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
// fires after the partial update of UpdatePanel
function EndRequest(sender, args) {
LoadMap();
}
var map = null;
function LoadMap()
{
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
}
</script>
You can also dynamically load the javascript, if you do not won to loaded if not the map displayed using ajax. Here is an example, that I load only one js. Modified it to load them all.
var map = null;
function LoadMap()
{
LoadScript("http://maps.google.com/maps/api/js?sensor=false&", function() {
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
});
}
function LoadScript(url, callback)
{
jQuery.ajax({
type: "GET",
url: url,
success: callback,
dataType: "script",
cache: true
});
};
Related
I got stuck in a problem. I am loading elements in a datalist dynamically. and i am trying to bind click event on a column using jquery. It works fine when i use master page with it. as it follows the page life cycle and loading jquery after child page data binding. But when i use it in a normal page(without master page) it does not allow me to perform desired action. I know why is this happening, the reason is jquery is being loaded before elements binding. so jquery is not able to bind click event since it is not able to find those controls.
binding elements already have "item" class in them
here is my jquery code:
$(document).ready(function () {
$('.item').click(function () {
//do something here
});
});
code behind:
protected void Page_Load(object sender, EventArgs e)
{
using (TestEntites db = new TestEntites())
{
IEnumerable<Template> Test = from t in db.Template
where t.Customer == clsuser.CustomerID
&& t.Region == user.RegionID
select t;
dlTemplateGroups.DataSource = Test;
dlTemplateGroups.DataBind();
BindTemplates(db);
}
}
$(document).ready(function () {
$('body').on('click', '.item' ,function () {
//do something here
});
});
$('body') make it more specific based on your html
I also had the same problem once and this problem really is a pain.
Here is my solution:
Instead of binding with click create a function for example:
function reBinding()
{
$('.item').on("click",function () {
//do something here
});
}
and call this function after data binding is done. it will be good if you are using update panel.
ScriptManager.RegisterStartupScript(rptGridAlbum.GetType, "scriptname", "reBinding();", True)
I have added the Gridview control on a webPage.
I am deleting any row (one row at a time) by calling PageMethod as follow:
<script type="text/javascript">
function Delete_Row(){
PageMethods.DeleteRow(row_id, GetTimeCallback, ErrorHandler, TimeOutHandler);
}
GetTimeCallback = function (result)
{
if (result) {
alert('Row is deleted');
// I want to refresh the Gridview here
}
}
<script type="text/javascript">
where "row_id" is primery key of the row.
It shows the alert perfectly but does not refresh the Gridview with one less deleted row.
what code should i write to Update the gridview?
NOTE: I dont want to refresh entire page.
Write CallBack Function to acheive this...You can find the Callback Functionality at http://msdn.microsoft.com/en-us/library/ms178208 and http://msdn.microsoft.com/en-us/library/ms178210
Edit:-
protected void Page_Load(object sender, EventArgs e)
{
String cbReference =Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
System.IO.StringWriter strDataGridHtml= new System.IO.StringWriter();
public void RaiseCallbackEvent(String eventArgument)
{
string idToBeDeleted=eventArgument;
//Write deleteCode
//DataBind the Grid
HtmlTextWriter htwObject = new HtmlTextWriter(strDataGridHtml);
GridViewControl.RenderControl(htwObject);
}
public String GetCallbackResult()
{
return strDataGridHtml.ToString();
}
Now as you see this strDataGridHtml will be sent to Javascript Function ReceiveServerData...
<script type="text/ecmascript">
function ReceiveServerData(rValue)
{
document.getElementById("divIDWhichEncapsulategridView").innerHTML = rValue;
}
</script>
Hope this Will Help you..As i don't i have your full code i can't write the exact one...but this should give you some idea on how to proceed...And also please go through the "CallBack" Functionality in order to understand this functionality to the fullest..
I have set of jquery files.like this :
<script src="js/PortalJs/jquery-ui-personalized-1.6rc2.min.js" type="text/javascript"></script>
<script src="js/PortalJs/inettuts.js" type="text/javascript"></script>
How is it possible to call these files after a specific update panel has been loaded.
To make calls on javascript side after the update panel loaded you use this standard code.
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// here you can load your scripts.
}
You can add at the EndRequest a code that loads the javascript, but take care to load it only ones. If the jQuery have conflicts try the jQuery.noConflict() command. http://api.jquery.com/jQuery.noConflict/
Sys.WebForms.PageRequestManager endRequest Event
MSDN Documentation
The endRequest event is raised after an asynchronous postback is finished and control has been returned to the browser. You can use this event to provide a notification to users or to log errors.
Reference - endRequest
Sample Code
<script type="text/javascript" language="javascript">
function EndRequestHandler(sender, args){
// here you can call the function provided by other user
}
<script
So you will have to write down the script loading function in javascript...
Here is a function that I use to add dependencies dynamically
function addDependencies(args) {
var head = document.getElementsByTagName('head')[0];
// todo refactor this logic
function exists(tag, src) {
var elms = document.getElementsByTagName(tag);
for (var i=0; i<elms.length; i++) {
if (elms[i].getAttribute('src') === src) {
return true;
}
}
}
for (var src in args) {
var isCss = /.+\.css$/i.test(src);
var isJs = /.+\.js$/i.test(src);
var tag = isCss ? 'link' : 'script';
if (!exists(tag, src)) {
if (isCss) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
var link = document.createElement(tag);
link.type = 'text/css';
link.href = src;
head.appendChild(link);
}
} else if (isJs) {
var script = document.createElement(tag);
script.type = 'text/javascript';
script.src = src;
script.onload = args[src]();
head.appendChild(script);
}
}
}
}
heres a demo
update panel has an onLoad event: http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.onload.aspx.
<asp:UpdatePanel OnLoad="upOnload" ...
you can load your javascript from the updatePanel Onload event in code behind like this:
protected void upOnload(object sender, EventArgs e)
{
Page.Header.Controls.Add(new LiteralControl("<script type='text/javascript' src='" + Page.ResolveUrl("~/js/PortalJs/inettuts.js") + "'></script>"));
}
I need to detect a postback in the frontend so I can use it with JQuery to change a class on page load. How can I do this?
You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
Stolen from this post:
On the server side have this
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
On client side this
if(isPostBack) {
// do your thing
}
I put this variable inside the header tag of my asp.net web forms page.
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
The var contains a Boolean. The comparison can probably be shortened.
Simple:
if you're using jquery it has to go after(jquery goes nuts otherwise):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
Then
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});
I have a cascading dropdown (3 of them) Type, Categories and Sub Categories. Type loads first and upon selection of Type, Category load and selection of Category, Sub Category loads.
Also i have 2 buttons, "Add Category" and "Add Sub Category" Upon clicking on these buttons, i call a JQuery Modal Form to add them. I use Webmethod in code behind to add them to database
This works perfectly in ASPX page.
Since I need use this in 3-4 pages, i thought of making the above as User control (ASCX). When i try to use this in a webpage, the webmethods in ASCX don't get called.
Is my approach correct? what should be done for my scenario
lOoking forward for your suggestions.
Thanks in advance
Karthik
i dont think you can have a WebMethod within a ASCX Control.
I solved it for my Problem like this:
AJAXBridge:
namespace Demo{
public partial class AjaxBridge : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod(EnableSession = true)]
public static string Control_GetTest()
{
return Control.GetTest();
}
}}
Control.ascx.cs
namespace Demo{
public partial class Control : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext.Current.Session["test"] = DateTime.Now.ToString();
}
// ALMOST A WEB METHOD
public static string GetTest()
{
return " is " + HttpContext.Current.Session["test"];
}
}}
Control.ascx
<script type="text/javascript">
var dataSend = {};
$.ajax({
type: "POST",
url: "AjaxBridge.aspx/Control_GetTest",
data: dataSend,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(data) {
alert("before");
},
success: function(data) {
alert("Page Load Time from Session " + data.d);
},
fail: function() {
alert("fail");
}
}); </script>
So you have one ASPX which acts basically like a Interface for all AJAX Methods in all your Web Controls. There also some advantages like having overview and control of all exposed WebMethods, which makes it a lot easier to handle security matters (eg. with Annotations).
Was your web method was a static method in the code behind that was marked with WebMethod attribute as described in the "Calling Static Methods in an ASP.NET Web Page" section here before you moved it? If so this type of webmethod only works at the page level and cannot be used in a usercontrol. For an alternative read the first two sections of this page.