To get value set in javascript in code behind - c#

I have following in html
<div id="dvAddToGrid" runat="server">
<table style="margin-left:80%">
<tr>
<td>
<asp:LinkButton ID="lnkAddToGrid" runat="server" Text="Add New" onclick="lnkAddToGrid_Click" OnClientClick="GetValues()" Font-Underline="True"></asp:LinkButton>
</td>
</tr>
</table>
</div>
I have following in javascript
function GetValues() {
// for (i = 1; i <= 5; i++)
// {
// $("#hdnTableValues")[0].value += document.getElementById("txtSerialNo_1").value+ ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtBookName_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtAuthor_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtPublisher_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtNoOfBooks_1").value + ",";
// $("#hdnTableValues")[0].value += document.getElementById("txtRemarks_1").value + "|";
// // }
document.getElementById("lblTableValues").innerHTML = $("#hdnTableValues")[0].value ;
}
In my code behind i have
protected void lnkAddToGrid_Click(object sender, EventArgs e)
{
DataTable dtBookList = new DataTable();
dtBookList.Columns.Add("SerialNo");
dtBookList.Columns.Add("BookName");
dtBookList.Columns.Add("Author");
dtBookList.Columns.Add("Publisher");
dtBookList.Columns.Add("NoOfBooks");
dtBookList.Columns.Add("Remarks");
string str = lblTableValues.Text ;
for(int i=1;i<5;i++)
{
DataRow dtRow = dtBookList.NewRow();
//hdnTableValues.Value
}
dvBookList.Visible = false;
dvAddToGrid.Visible = false;
}
Problem is i am getting values in lblTableValues in js.But in code behid it does not contain any values its value is "".Can anybody help to get the value contained in hdnTableValues in click event in code behind.

You can use a hidden input with runat="server" to handle this. Store the value to the hidden field in JavaScript. And you can access the field value in C# code behind.
HTML
<input type="hidden" id="txtHidData" runat="server" />
JavaScript
document.getElementById ( "txtHidData" ).value = "your value";
C#
string valueInCodeBehind = txtHidData.Value;

Use the asp:HiddenField control like this: (jquery example)
in the page or control:
<asp:HiddenField ID="Hidden1" runat="server" Value="blank" />
<asp:PlaceHolder runat="server">
<script type ="text/javascript">
$(function () {
//get the id of the hidden control
var clientID = "<%= Hidden1.ClientID %>";
$("#" + clientID).val("this is from the client");
});
</script>
</asp:PlaceHolder>
In a button or submit method in code behind:
Debug.WriteLine("val: " + Hidden1.Value);

Related

Button in asp.net web forms dont fire event

can you help me with something i struggle for 4 days, button event doesn't fire :( In the MasterPage i use this to add control
<Login:UserLogin runat="server" ID="UserLogin" EnableViewState="false" > </Login:UserLogin>
and the control is this
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserLogin.ascx.cs" Inherits="BookApartmentsPortal.controls.UserLogin" %>
<%# Register TagPrefix="MultiLanguage" Namespace="MultiLanguage.multilanguage" %>
<%--
<script type="text/javascript">
function DeleteKartItems() {
var inputEmail = $("#ctl00_UserLogin_txtEmailVal").val();
var user = {
email: "s.krastanov",
password: "1"
};
$.ajax({
type: "POST",
url: 'PublicDefault.aspx/Getvalues',
data: JSON.stringify({ person: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
$("#ctl00_PublicDefault_buttonLog").Click();
}
</script>--%>
<h3>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral13" runat="server" Resource="669" />
</h3>
<form action="/" method="POST" id="formasd">
<div class="">
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral14" runat="server" Resource="858" />
<%--user name input field--%>
<input type="text" class="modal-input" runat="server" size="20" id="txtEmailVal"
name="txtEmail" />
<%-- <asp:TextBox runat="server" CssClass="modal-input" ID="txtEmailVal" ></asp:TextBox> --%>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral21" runat="server" Resource="205" />
<%--password input field--%>
<%--<input type="password" class="modal-input" runat="server" size="1" maxlength="20" id="txtPassword" />--%>
<asp:TextBox runat="server" CssClass="modal-input" TextMode="Password" ID="txtPassword"
MaxLength="20" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server">
</asp:Label>
<asp:Panel ID="panelLogin" runat="server" DefaultButton="btnLogon">
<asp:Button runat="server" ID="btnLogon" Text="Click" CssClass="login-btn" OnClick="btnLogon_Click"></asp:Button>
</asp:Panel>
<%-- <button class="login-btn" runat="server" id="btnLogon" name="btnLogon" onclick="DeleteKartItems()">
<i class="fa fa-paper-plane"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
</button>--%>
<div id="divResult">
</div>
</div>
</form>
<asp:HyperLink ID="LoginFB" Target="_blank" runat="server" CssClass="btn btn-block btn-social btn-facebook fb-login">
<i class="fa fa-facebook"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral27" runat="server" Resource="1306" /></asp:HyperLink>
<a href="#lost-pass" class="button-modal various-login"><i class="fa fa-lock"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral22" runat="server" Resource="164" /></a>
<a href="#reg" class="button-modal reg"><i class="fa fa-user"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral23" runat="server" Resource="1271" /></a>
Backend is this:
public partial class UserLogin : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
Response.Write("you click");
}
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
LoginFB.NavigateUrl = "https://www.facebook.com/v2.0/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + ConfigurationManager.AppSettings["URL"].ToString() + "/Publish/UserFB.aspx&response_type=code&state=1";
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
//btnLogon.ServerClick += new EventHandler(btnLogon_Click);
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
//btnLogon.ServerClick += new CommandEventHandler(btnLogonClick);
// btnLogon.Command += btnLogon_Click;
}
public void btnLogon_Click(object sender, EventArgs e)
{
Label1.Text = "submit button is press";
// if (LoginSet == false )
// {
string Name = txtPassword.Text;
string Dev = txtEmailVal.Value;
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal.Value.Trim(), txtPassword.Text.Trim(), true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now;
FormsAuthentication.RedirectFromLoginPage(txtEmailVal.Value.Trim(), false);
Session["LoginUserName"] = txtEmailVal.Value.Trim();
// _loginSet = true;
}
else
{
// _loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
// _loginSet = false;
}
//}
}
}
This control is for login form and i just cant get the values from input boxes because event don't trigger. One idea was to make AJAX post to static method but after that i cant make new session with this variables.
I try everything and this button just doesn't fire the event. I don't know what to do next, can you help me.
Ok after one more day of struggle, i manage to make a little walk around path:
In the first step i made a Button to fire event (javascript function) and make cookie, after that i make click event for actual asp:Button :
<script type="text/javascript">
function LoginClicked() {
var inputEmail = $("#txtEmail").val();
var inputPass = $("#txtPassword").val();
if(inputEmail != "" && inputPass != ""){
var userSet = inputEmail + "&" + inputPass;
setCookie("UserSettings", userSet, 1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
$("#ctl00_UserLogin_btnLogon").click();
}
}
</script>
And here is the buttons:
<asp:Panel runat="server" ID="panekl">
<asp:Button runat="server" ID="btnLogon" UseSubmitBehavior="false" CssClass="no-display" ></asp:Button>
</asp:Panel>
<button class="login-btn" id="btnLogon1" name="btnLogon1" onclick="LoginClicked()">
<i class="fa fa-paper-plane"></i><MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
And in the back end, i get the cookie, split it, and check for validation:
public void btnLogon_Click()
{
if (LoginSet == false )
{
string[] txtSome = Request.Cookies["UserSettings"].Value.Split('&');
if (Request.Cookies["UserSettings"] != null && txtEmailVal != "" && txtPassword != "")
{
txtEmailVal = txtSome[0].Trim();
txtPassword = txtSome[1].Trim();
}
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal, txtPassword, true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Session["IdUserLogin"] = txtEmailVal;
_loginSet = true;
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Label1.Text = "submit button is press";
}
else
{
_loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
_loginSet = false;
}
}
}
This was the only way i figured out to get values from the control.

load codebehind Gridview dynamically

I am generating this tags (IT,Marketing....) dynamically(codebehind) from the sql using linq to sql.
And when you click on any of the the tabs it will show the gridview as per table created in database.
But the gridview binding is done during page_load event, so everything is generated during page_load, now when you click any of the blue tabs , it will show you pre-generated gridviews.
Now i want to generate or load gridviews when i clck on [+] sign of any of the tabs and not during the page load
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div id="CONTAINER" onclick="">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="clickable mfiles" onclick="showHide('subm');changesign('signm');">
<span id="signm" class="plusMinus">[+]</span><span> M-Files<br />
</span>
</div>
<div id="subm">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
<script>
function showHide(id) {
__doPostBack('UpdatePanel1', id);
var el = document.getElementById(id);
//if (el && el.style.display == 'block') {
// el.style.display = 'none';
//}
//else {
// el.style.display = 'block';
//}
}
function changesign(id1) {
var xy = document.getElementById(id1);
if (xy.innerHTML == "[-]") {
xy.innerHTML = "[+]";
}
else {
xy.innerHTML = "[-]";
}
}
</script>
banckend code:
protected void Page_Load(object sender, EventArgs e)
{
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var depts = context.spi_GetNoOfDept();
PlaceHolder1.Controls.Clear();
int i = 1;
foreach (spi_GetNoOfDeptResult dept in depts)
{
Literal div = new Literal();
Contact deptinfo = new Contact();
deptinfo.NAME_LAST = dept.DEPT_NAME;
deptinfo.DEPT_ID = dept.DEPT_ID.ToString();
div.Text = "<div class=\"even clickable\" onclick=\"showHide('sub" + dept.DEPT_ID + "');changesign('sign" + dept.DEPT_ID + "');\">";
div.Text += "<span id=\"sign" + dept.DEPT_ID + "\">[+]</span><span>" + dept.DEPT_NAME + "</span>";
div.Text += "</div>";
div.Text += "<div id=\"sub" + dept.DEPT_ID + "\" style=\"margin-left:15px ;\">";
//GridView gd = CreateDynamicTable(dept.DEPT_ID);
i++;
PlaceHolder1.Controls.Add(div);
PlaceHolder1.Controls.Add(new LiteralControl("</div>"));
}
private GridView CreateDynamicTable(int x)
{
GridView gd = new GridView();
gd.ID = "grd" + x;
gd.AlternatingRowStyle.CssClass = "altrowstyle1";
gd.RowStyle.CssClass = "rowstyle1";
gd.HeaderStyle.CssClass = "grdhdr";
gd.GridLines = GridLines.None;
List<Contact> contacts = new List<Contact>();
CONTACT_INFODataContext context = new CONTACT_INFODataContext("Data Source=BPM-IT116;Initial Catalog=FORM_GET;Persist Security Info=True;User ID=spreader;Password=Red_Sky");
var persons = context.spi_GetContacts();
var items = context.spi_GetDept(x);
var depts = context.spi_GetNoOfDept();
foreach (spi_GetDeptResult item in items)
{
Contact contact = new Contact();
contact.NAME_LAST = item.NAME_LAST;
contact.NAME_FIRST = item.NAME_FIRST;
contact.PHONE_CELL = item.PHONE_CELL;
contact.ADDRESS = item.ADDRESS;
contact.APT = item.APT;
contact.DEPT_ID = item.DEPT_ID.ToString();
contact.DEPT_NAME = item.DEPT_NAME;
contacts.Add(contact);
//ddl_db.Items.Add(new ListItem(person.NAME_FIRST));
}
gd.CssClass = "gdmain";
gd.DataSource = contacts;
gd.DataBind();
return gd;
}
If you use a Multiview control for your tab container then you should be able to bind your code to load the Gridview to the ActiveViewChanged event and change your ActiveViewIndex property for that Multiview when your users navigate between your tabs.

hidden field in code behind not refreshing

// problem refreshing value
code behind file dynamically creates a checkbox, aspx file contains javascript that is invoked
when the checkbox is checked see below:
//javascript
function checkBoxClicked(sender)
{
var hdnfldVariable = document.getElementById('hcompare');
if (sender.checked == true) {
sCompareAuditVersion = sender.value;
}
document.getElementById('hcompare').value = sCompareAuditVersion;
}
//aspx file -
I have used a hidden field to pass to code behind file and have initialize value with 'x' to
//ensure that value changes
<form id="form1" runat="server">
<div class="lowSectionClass">
<asp:HiddenField id="hcompare" value="X" runat="server">
</asp:HiddenField>
//code behind file dynamically builds chekbox
public class Report : Page
{
protected HiddenField hcompare;
private string populateCalculations(int tabID, int programID, int participantID)
{
string str = "";
str = ((((str + "<br /><br /><center><table cellpadding='0' cellspacing='10'>" + "<tr class='HeadingCellText'>") + "<td>Audit Version</td>" + "<td></td>") + "<td>Calculation Set</td>" + "<td></td>") + "<td>Run Calcs/Print Report/Print CSB</td>" + "<td></td>") + "<td>Compare?</td>" + "</tr>";
DataTable infoList = new DataTable();
infoList = new ReportClass().GetInfoList(programID);
if (infoList.Rows.Count > 0)
{
for (int i = 0; i < infoList.Rows.Count; i++) // 1 = a audit, 2 = b audit, 3 = c audit.....
{
if ((i % 2) == 0) //audit 'a' = 0, audit 'b' = 1
{
str = string.Concat(new object[] { str, "<td>", infoList.Rows[i]["dtCalcDate"], "</td>" }) + "<td></td>";
str = string.Concat(new object[] { str, "<td>Run Calcs | <a href=\"javascript:setPrintVariables(", programID, ",", participantID, ",'",
infoList.Rows[i]["sAuditVersion"].ToString(), "');section_CallBack('build');\">Print Report</a> | <a href=\"ReportViewer.aspx?ProgramID=", programID, "&ParticipantID=", participantID, "&AuditVersion=",
infoList.Rows[i]["sAuditVersion"].ToString(),"&CompareAuditVersion=", hcompare.Value,"&csb=1\" target='blank'>Print CSB</a></td>"
}) + "<td></td>";
// above is where the hidden field is assigned to be passes in as a parameters and the value is not being updated
// below is where the checkbox is created and assigned function 'checkBoxClicked(this)'
str = string.Concat(new object[] { str, "<td><input id='Checkbox", i, "' tabindex='", i, "' value='", infoList.Rows[i]["sAuditVersion"].ToString(), "' onclick='checkBoxClicked(this)' type='checkbox' /></td>" }) + "</tr>";
}
}
}
return (str + "</tfoot>" + "</table></center>");
}
}
Set clientidmode = static for your hidden field
<form id="form1" runat="server">
<div class="lowSectionClass">
<asp:HiddenField id="hcompare" value="X" clientIdMode="static" runat="server">
</asp:HiddenField>
</div>
</form>

Asyncupload control of AjaxControlToolkit

I am using asyncupload control of AjaxControlToolkit and I want to check the file to be uploding is already exists or
not on server.
How we can do this?
Please help me out.
<!-- Client side code for control-->
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
<!-- Control Code in aspx-->
<tr>
<td></td>
<td>
<cc1:AsyncFileUpload ID="FileUpload2" Width="265px" runat="server"
OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red"
ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../../images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label>
<asp:HiddenField ID="hdnField" runat="server" value=""/>
</td>
</tr>
//.CS Code for ayncupload control
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath="C:\Documents\temp.txt"
if(File.Exists(filePath))
{
hdnField.value="1";//Not able to access this value
}
}
Thanks!!
you just need to set your hidden field value at client side script.
See I have made little changes in your server side code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath = "C:\\Documents\\temp.txt";
string hiddenValue = "0";
if (File.Exists(filePath))
{
hiddenValue = "1";
}
//This script will set required value for hidden field.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SetHiddenField", String.Format("top.$get('{0}').value = '{1}'", hdnField.ClientID, hiddenValue), true);
}
Make changes in your script location as follow:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
Check if the file exists using the following:-
File.Exists
You can compare based on the filename.

GeoMap not working inside update panel

I am using geomap-linechart api in my application.. I want to view the map and the chart on a drop down selected index changed event.. It doesn't work if i put it inside update panel.. it becomes blank.. but it woks fine if i put the control outside the update panel.. Is there any reason or suggestion for this prob?? is it not possible to use the geomap inside update panel??
this is my code..
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script src='http://maps.google.com/maps?file=api&v=2&key=ABCDEFG' type='text/javascript'></script>
<script type='text/javascript'>
google.load('visualization', '1', { 'packages': ['geomap'], 'language': 'fr'});
var countryCode;
// map function
function DrawWorldMap(country, lat, lang, name, count, usercount, user, bandwidth, vtitle, htitle, title1, title2) {
try {
var data = new google.visualization.DataTable();
data.addRows(count);
data.addColumn('string', 'Country');
data.addColumn('number', 'BandWidth');
var contry = country.split(',');
var band = bandwidth.split(',');
for (var i = 0; i < count; i++) {
data.setValue(i, 0, contry[i]);
}
for (var h = 0; h < count; h++) {
data.setValue(h, 1, Number(band[h]));
}
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('<%=map_canvas.ClientID%>');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
var lati = lat;
var langi = lang;
var loop = count;
google.visualization.events.addListener(
geomap, 'regionClick', function (e) {
countryCode = e['region'];
CreateCountryMap(lati, langi, name, loop, usercount, country, user, bandwidth, vtitle, htitle, title1, title2);
});
}
catch (exception) {
alert('drawworldmap: ' + exception);
}
drawVisualization(user, bandwidth, usercount, vtitle, htitle, title1, title2); // here am calling the chart function..
}
//chart function
function drawVisualization(User, Bandwidth, counts, vtitle, htitle, title1, title2) {
try {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', title1);
data.addColumn('number', title2);
var username = User.split(',');
var BandWidth = Bandwidth.split(',');
for (var i = 0; i < counts; i++) {
data.addRow([String(username[i]), Number(BandWidth[i])]);
}
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById('<%=visualization.ClientID%>')).
draw(data, { curveType: "function", pointSize: 5, title: 'User Chart', titlePosition: 'out',
width: 400, height: 350, backgroundColor: 'AliceBlue',
vAxis: { maxValue: 100, title: vtitle }, fontSize: 8, hAxis: { title: htitle }
}
);
}
catch (exception) {
alert(exception);
}
}
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlusername" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlusername_SelectedIndexChanged" Height="17px"
Width="132px"> </asp:DropDownList>
<div id="visualization" align="center" style="border: thin solid grey;" runat="server"> </div>
<div id='map_canvas' style="border: thin solid grey;" align="center" runat="server"> </div>
<asp:Label ID="lblmap" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
and i'm calling the drawworldmap function from code behind like this..
ScriptManager.RegisterStartupScript(lblmap, this.GetType(), "js2", "google.setOnLoadCallback(DrawWorldMap('" + contry + "','" + city + "','" + langitude + "','" + longitude + "'," + count + "," + usercount + ",'" + username + "','" + bandwidth + "','Bandwidth','UserName','User','BandWidth'));", true);
Pls help if you have any idea..
Thank you..
First solution is call function of load google map again, like initMap() function from javascript.
second solution is make iframe page from map and load it when you click on div of map.
your problem is in update panel it is not loading properly.
so.When you click on div of map again load map by first solution.
other wise use second soluction by loading iframe.
I have done both this thing in my projects.
Hope this will help you.
<script type="text/javascript">
function ActiveTabChanged(sender, e) {
if (sender.get_activeTab().get_headerText().toLowerCase().indexOf('contact') > -1) {
var FrameSrc = ('<%=SetFrameSrc() %>');
document.getElementById('<%=ifrmMap.ClientID %>').src = FrameSrc;
}
}
</script>
<iframe id="ifrmMap" runat="server" height="324px" width="462px" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>
At Code Behind
/// <summary>
/// Get the iframe source when contact tab active.
/// </summary>
/// <returns></returns>
public string SetFrameSrc()
{
string strSrc = string.Empty;
if (!string.IsNullOrEmpty(queryID))
{
strSrc = //Add Google Map New page url;
}
return strSrc;
}
When you select map from dropdown call this javascript function on selected indexchanged.
put iframe where you put div of map right now. and put map functionality over to new page.
which is loaded in this iframe.and last function is code behind function where you have to set your new page where you
have write map code.

Categories