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.
Related
Using ASP.net and WebForms i am trying to store the user's location (Latitude, Longitude) to a database. This presents the problem:
How can i get the user's latitude and longitude into a place where server-side ASP.net code can then save it into a database.
What have you tried?
I don't care which technology is used; i just need their location. My first attempt was to try to use Google Maps in order to access the current location. And while i can use javascript in the browser to get ahold of the current location, i cannot figure out how to transfer that information to the server.
Here's the sample code of my first attempt:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var long = 0;
var lat = 0;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
long = e.latLng.lng();
lat = e.latLng.lat();
alert("Latitude: " + lat + "\r\nLongitude: " + long);
});
}
</script>
<div id="dvMap" style="width: 300px; height: 300px">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</body>
</html>
And below is the .aspx code-behind file. We save the longitude and latitude to the database during the Click event of the button:
protected void Button1_Click(object sender, EventArgs e)
{
//TODO: Ask Stackoverflow how to get these values from browser-land javascript
Double latitude = 0;
Double longitude = 0;
SqlConnection con = new SqlConnection();
con.ConnectionString = "#Data Source=(LocalDB)\v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
string query1 = "insert into Courses(longi,lati) values (#lati, #longi)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#lati", latitude);
cmd1.Parameters.AddWithValue("#longi", longitude);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}
Location API
Nothing says i need to be using Google Maps. I know that HTML has a Location API accessible somewhere, somehow. Is there an established way that the browser's Location API can be used to feed the user's location to the server in ASP.net?
Add asp hidden fields, with runat="server" to hold the lat and lng. When you get the lat and lng in your javascript simply populate the hidden fields with those values. Then you can reference the hidden fields values directly in your OnClick handler.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var long = 0;
var lat = 0;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
long = e.latLng.lng();
lat = e.latLng.lat();
document.getElementById("lat").value = lat;
document.getElementById("lng").value = long;
alert("Latitude: " + lat + "\r\nLongitude: " + long);
});
}
</script>
<form id="myForm" runat="server">
<div id="dvMap" style="width: 300px; height: 300px">
</div>
<asp:HiddenField ID="lat" runat="server" />
<asp:HiddenField ID="lng" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
//TODO: Ask Stackoverflow how to get these values from browser-land javascript
Double latitude = Convert.ToDouble(lat.Value);
Double longitude = Convert.ToDouble(lng.Value);
SqlConnection con = new SqlConnection();
con.ConnectionString = "#Data Source=(LocalDB)\v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
string query1 = "insert into Courses(longi,lati) values (#lati, #longi)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#lati", latitude);
cmd1.Parameters.AddWithValue("#longi", longitude);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}
I relly need your help )) I have a gridview which is bounded to a SQL database. How can I open a pop-up by clicking on image or SQL ID number in my table?
Script v
<script>
$(function () {
var dialog, form,
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
name = $("#name"),
email = $("#email"),
password = $("#password"),
allFields = $([]).add(name).add(email).add(password),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid && checkLength(name, "username", 3, 16);
valid = valid && checkLength(email, "email", 6, 80);
valid = valid && checkLength(password, "password", 5, 16);
valid = valid && checkRegexp(name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter.");
valid = valid && checkRegexp(email, emailRegex, "eg. ui#jquery.com");
valid = valid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function () {
dialog.dialog("open");
});
});
</script>
This is my gridview:
<asp:GridView id="Objektkatalog" runat="server" OnClick = "Page_Changed"
AllowPaging="true" PageSize="4" DataSourceID="SqlDataSource2"
DataKeyNames="ObjektID" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound">
<columns>
<asp:TemplateField>
<ItemTemplate>
Nr. <%#Eval("ObjektID")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" Height="55px" Width="55px" ImageUrl='<%# Eval("Picture","~/Objekte/{0}") %>' /> //it comes to a second itemTemplate, dono why i cant add this in code section...
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
And well, if I use this button
<button id="create-user">Create new user</button>
then it works fine and I open my EditTmplate, where I can change all data in my SQL database, but I have to do the same pop up by clicking on every element of my table; I know its a couple of lines or just 1 command to change, but id very bad in JS, jQuery etc.=) I will be very glad for your help.
I still made some picture to explain it better =) http://ipic.su/img/img7/fs/dsadsadsada.1406036339.jpg
Put the code for opening popup in below function -
$(document).on("click", "[id*=idViewPopup]", function () {
});
Here [id*=idViewPopup] is nothing but ID of the object in the GridView. so, when I click on the image with ID = idViewPopup, the model popup will be displayed.
Check below link for detailed example -
http://www.aspsnippets.com/Articles/Display-GridView-Row-details-inside-jQuery-Dialog-Modal-Popup-in-ASPNet.aspx
I am having such a rough time accomplishing this and all the research I'm doing is not turning out positive. In short, I need to send an array of markers from my code to my MVC view (through the model and setting it as a hidden field) so that the Google map can use this array to place markers on the map. I have tried building it as a List and then using JSON serialization to turn it to a string, but the format just won't turn out and won't be recognizable to the Google API. Has anyone done this before successfully??
Here is my updated code based on CodeMonkey's answer, but the markers still aren't placing. I think it's happening somewhere in the addMarker function...
var lat = $("#Latitude").val();
var lng = $("#Longitude").val();
var myOptions = {};
var map = null;
var marker = null;
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function map_initialize() {
var myLatlng = new google.maps.LatLng(lat, lng);
myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
#foreach (var item in Model.AllSearchResults)
{
<text>try
{
var lat = '#item.Latitude';
var lng = '#item.Longitude';
var name = '#item.Name';
var url = '#Url.Action("GetMarker", "Base")';
var model = { "Latitude": lat, "Longitude": lng, "Name": name };
$.ajax({
type: "POST",
data: model,
dataType: "json",
url: url,
success: function (data) {
geodata = data;
JSONString = JSON.stringify(geodata);
var valuesToPush = new Array();
valuesToPush[0] = data.Latitude;
valuesToPush[1] = data.Longitude;
valuesToPush[2] = data.Name;
markers.push(valuesToPush);
addMarker();
},
error: function () {
alert("fail");
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var name = markers[i][2];
var location = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + name + '</p></div>';
var marker = new google.maps.Marker({
position: location,
map: map,
title: name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', map_initialize);
I was able to do a combo server side/client side approach using the following link as a guide: http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html
Thanks for Code Monkey's input!!
You can reference my front-end JS code at this URL: http://www.wallodex.com/WallodexAdmin/Map/10
This is how I use it on the VIEW:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CloudClaims Administration - Site Visits</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgJDbn0VP_AnX4HsXSjN3cIn0MoEJ4vOw&sensor=false"></script>
<script type="text/javascript" src="../../js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../../js/json2.js"></script>
<script type='text/javascript'>
var DISPLAY_COUNT = 20;
var myOptions = {};
var markerArray = new Array();
var map = null;
//var geocoder = null;
var marker = null;
var g_ctr = 0;
var last_used_address = "";
var splitURLs = {};
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function initialize() {
myOptions = {
center: new google.maps.LatLng(38.5111, -96.8005),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//geocoder = new google.maps.Geocoder();
#foreach (var item in Model)
{
<text>try
{
var ip = '#item';
var url = 'http://api.ipinfodb.com/v3/ip-city/?format=json&key=6d0759103a4ec817ffda18dfba4eafe853125d6960dedffdcfa4a428774d871d&ip=' + ip + '&callback=?';
$.getJSON(url,
function (data) {
if (data['statusCode'] == 'OK') {
geodata = data;
JSONString = JSON.stringify(geodata);
//callback();
//alert(data.regionName);
var valuesToPush = new Array();
valuesToPush[0] = data.latitude;
valuesToPush[1] = data.longitude;
valuesToPush[2] = data.cityName + ', ' + data.regionName;
valuesToPush[3] = data.ipAddress;
markers.push(valuesToPush);
addMarker();
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var cityState = markers[i][2];
var ipAddress = markers[i][3];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + cityState + '<br/>' + ipAddress + '</p></div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " \n Location: " + cityState
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fadeInbox").hide().fadeIn(4000);
$("#map_canvas").hide().fadeIn(4000);
$(".subscriberList").hide().fadeIn(8000);
});
$(window).load(function () {
$("#loading").css('visibility', 'hidden');
});
</script>
<style type="text/css">
.infowindow
{
background-color: Yellow;
text-align: left;
padding: 0px, 0px, 0px, 0px;
margin: 0px, 0px, 0px, 0px;
}
.fadeOutbox, .fadeInbox, .fadeTobox
{
padding: 10px;
margin: 4px;
border: 1px solid blue;
width: 250px;
height: 50px;
background-color: #000000;
color: white;
font: georgia;
}
.clear
{
clear: both;
}
</style>
</head>
<body onload="initialize();">
<form id="form1" runat="server">
<asp:panel id="Panel1" runat="server" style="height: 600px;">
<asp:Literal ID="js" runat="server"></asp:Literal>
<table width="100%" align="center" border="1">
<tr bgcolor="#1569C7" align="center">
<td colspan="2">
<font color="white">CloudClaims™ - Site visitors - Last X days</font>
</td>
</tr>
<tr align="center">
<td width="80%">
<div id="map_canvas" style="width: 100%; height: 620px; margin-bottom: 0.5px;"></div>
</td>
<td align="center" valign="bottom" bgcolor="#FFBD82">
<asp:Label runat="server" id="errors"/>
<div>
#{Html.RenderAction("Subscribers");}
</div>
<div align="center" class="fadeInbox">
<b>DEBUGGING</b><br />
<asp:Label runat="server" id="ajaxtest"/>
</div>
</td>
</tr>
</table>
</asp:panel>
</form>
</body>
</html>
And this is my CONTROLLER (I convert IP ADDRESSES to gMap objects on the front-end but you get the idea...):
public ActionResult Map(int id)
{
try
{
using (var db = new CloudClaimsEntities())
{
DateTime dateFrom = (id != null && id > 1) ? DateTime.Now.AddDays(-id) : DateTime.Now.AddDays(-1);
List<string> IPAddresses = new List<string>();
IPAddresses = db.IPLogs
.Where(i => i.timeStamp <= DateTime.Now)
.Where(i => i.timeStamp >= dateFrom)
.Select(i => i.IPAddress)
.ToList();
return View(IPAddresses);
}
}
catch
{
return View();
}
}
I am using the following code to add Marker in Google Maps (API V3) ,
I use XML file for store locations
protected void Page_Load(object sender, EventArgs e)
{
string locations = "";
string lastlat = "", lastlng = "";
XDocument xmlDoc = XDocument.Load(Server.MapPath("~/App_Data/Map.xml"));
var query = from st in xmlDoc.Descendants("Position")
select st;
foreach (var p in query)
{
lastlat = p.Element("Latitude").Value;
lastlng = p.Element("Longitude").Value;
locations += "var marker = new google.maps.Marker({position: new google.maps.LatLng("
+ p.Element("Latitude").Value + ","
+ p.Element("Longitude").Value + "),info:\""
+ p.Element("Name").Value + "\",title:\""
+ p.Element("Name").Value + "\",map: map});marker.setMap(map)";
}
Label1.Text = locations;
js.Text = #"<script type='text/javascript'>function initialize() { var myLatlng = new google.maps.LatLng(" + lastlat + "," + lastlng + "); var myOptions = {zoom: 16, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById('map'), myOptions);" + locations + "marker.setMap(map);}</script>";
}
and this code
<body onload="initialize()">
<form id="form1" runat="server">
<table width="100%" border="1">
<asp:Literal ID="js" runat="server"></asp:Literal>
<div id="map" style="width:995px;height:600px;"></div>
</table>
</form>
</body>
but do not show map in webpage!!!
This gives two error
Uncaught SyntaxError: Unexpected token var
Uncaught ReferenceError: initialize is not defined
You're missing a semicolon after
var myOptions = {zoom: 16, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }
I bet it'll work if you add that in.
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);