google maps API v3 doen't respond - c#

I'm new here.
I'm trying to make an application that calculates distance and driving time between two adresses using google maps API.
My problem is that google DirectionsService() doesn't seem to respond. and I can't figure it out. I have been trying to figure it out for one week now.
I hope you guys can help.
the problems seems to be in gmapApi.js
here is my code.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function postbackObj() {
var orig = document.getElementById('<%= txbOrigin.ClientID %>').value;
var dist = document.getElementById('<%= txbDestination.ClientID %>').value;
var temp = showLocation(orig, dist);
__doPostBack('gmAPIObj',temp);
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript">< /script>
<script type="text/javascript" src="gmapApi.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txbOrigin" Text="" runat="server" />
<asp:TextBox ID="txbDestination" Text="" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Search" OnClientClick="postbackObj()"/>
<p>
< asp:Label runat="server" ID="lblPrint" />
</p>
</div>
</form>
</body>
</html>
gmapApi.js
function showLocation(orig, dist) {
var directionService = new google.maps.DirectionsService();
var t = "";
var request = {
origin: orig,
destination: dist,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionService.route(request, function (response, status) {
if (status != google.maps.DirectionsStatus.OK) {
alert(status + " \nreq. failed.");
}
else {
t = request.origin + ';' + request.destination + ';' + response.routes[0].legs[0].distance.value + ';' + response.routes[0].legs[0].duration.value;
}
});
return t;
}
the response variable is null and the status variable is emptystring in the directionService.route(request, function (response, status)
I have tried to change to without lock. And I have tried to place the tags in the body tag without lock.
the rendered html code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
<script type="text/javascript">
function postbackObj() {
var orig = document.getElementById('txbOrigin').value;
var dist = document.getElementById('txbDestination').value;
var temp = showLocation(orig, dist);
__doPostBack('gmAPIObj',temp);
}
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="gmapApi.js"></script>
</head>
<body>
<form method="post" action="Default.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MjMyMzMwNTZkZHxi8IJlhy7bL8nAZqZfL2Vh4Yr8uF80ja6jX9Ypc87B" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBALsorucDwLTmobsAwK0weWLAwLCi9reA32PxME86E6mQhRTgBkF7cdktbiURIpf/IzKvAs5PHwI" />
</div>
<div>
<input name="txbOrigin" type="text" value="tilst" id="txbOrigin" />
<input name="txbDestination" type="text" value="aarhus" id="txbDestination" />
<input type="submit" name="btnSubmit" value="Search" onclick="postbackObj();" id="btnSubmit" />
<p>
<span id="lblPrint"></span>
</p>
</div>
</form>
</body>
</html>
thanks in advance.

requesting the directionService is an asynchronous process, your variable t inside the function showLocation will not be modified by the call of directionService.route()
call __doPostBack('gmAPIObj',t) from within the successfull callback of directionService.route() instead.
function postbackObj() {
var orig = document.getElementById('txbOrigin').value;
var dist = document.getElementById('txbDestination').value;
showLocation(orig, dist);
}
//-----
function showLocation(orig, dist) {
var directionService = new google.maps.DirectionsService();
var t = "";
var request = {
origin: orig,
destination: dist,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionService.route(request, function (response, status) {
if (status != google.maps.DirectionsStatus.OK) {
alert(status + " \nreq. failed.");
}
else {
t = request.origin + ';' + request.destination + ';' + response.routes[0].legs[0].distance.value + ';' + response.routes[0].legs[0].duration.value;
__doPostBack('gmAPIObj',t);
}
});
}

Related

Upload multiple files - Incomplete script

Just got my hand on a script that I wish to use to upload files in my application. I can't really use any of the existing controls as I need to do some specific alterations to paths and stuff before the files are uploaded.
I have the following (incomplete) code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="../plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="../plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<form enctype="multipart/form-data">
<span class="btn btn-file btn-primary" id="media-upload-btn">
<span class="fileupload-new" title="Accepted formats (.gif, .jpeg, .png)">Choose image(s)</span>
<span class="fileupload-exists">Choose another image</span>
<input id="user-file-to-upload" type="file" name="file" accept="image/gif, image/jpeg, image/png"/>
</span><br /><br />
<input type="button" onclick="upload();" value="Upload" />
</form>
</div>
</form>
<script type="text/javascript">
function upload() {
alert("test");
// var acceptedFileSize = $('#upload-image-size').val();
var acceptedFileSize = 10000;
alert(acceptedFileSize);
if (window.FormData !== undefined) {
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
var fileSize = files[i].size;
sp.base.log('fileSize(b): ' + fileSize);
sp.base.log('acceptedFileSize(kb): ' + acceptedFileSize);
if (parseInt(fileSize) > (parseInt(acceptedFileSize) * 1024)) {
$('#btnUpload').button('reset');
sp.base.show('The file is too large!<br>Cant be larger than ' + (parseInt(acceptedFileSize) / 1024) + ' MB. ' + ' and the current file size is ' + Math.round((parseInt(fileSize) / 1024 / 1024)) + ' MB.', 'error', 12000);
return false;
}
}
var url = "upload2.aspx";
sp.base.call(
'POST',
url,
data,
function (returnData) {
alert("Works");
onSuccessUploadImage(returnData, callback);
},
null,
function () {
// onError
alert("Error");
$('#btnUpload').button('reset');
},
null,
true,
false
);
}
}
</script>
Right now, I'm unsure of how to actually collect the files into the files object, and I would also like to be able to add multiple files, not just one.

How to retrieve binarydata source of an image in asp.net

I want to get image preview before uploading any image in my asp.net webform. I am doing this by the following code. But after clicking Save button I want to upload the image to the server. In my codebehind I am getting src="" for <img>. What can I do to get the binarydata back to save my file.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var link = $(fileInput).siblings('.thumb').attr('src');
alert(link);
var img = document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br />
<img id="thumbnil" class="thumb" style="width: 20%; margin-top: 10px;" src="" alt="image" runat="server"/>
<asp:Button runat="server" Text="Save" OnClick="Unnamed_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Thanks in advance..
### Undated whole Answer ###
Option 1:
dont read the img-tag src-attribute, the client cant update it on server side and it wont be "post-back". use an input field like this
<form...>
...
<input class="image-data" type="hidden" id="imageString" runat="server" />
...
</form>
and in the Js-Code add this dataurl as value of this field.
...
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
//... add this, it's searches for the input-field, to be able to post the String to the Server
$(".image-data").val(e.target.result);
};
...
Update:
On the Server you can read the Data like this.
string imageData = imageString.Value;
Option 2:
you could also do this:
alter your asp.net-file
<!-- add enctype=... -->
<form id="form1" runat="server" enctype="multipart/form-data">
...
<!-- add name=... -->
<input type="file" accept="image/*" onchange="showMyImage(this)" name="uploadImage" />
...
in the Codebehind:
HttpPostedFile imageFile= Request.Files["uploadImage"];
if (imageFile && imageFile.ContentLength > 0)
{
// ... Use the imageFile variable as you please
}
Which Option depends, what you want to do with the data.

How to set random id for dynamic created textbox and div [duplicate]

This question already has answers here:
generate random string for div id
(17 answers)
Closed 8 years ago.
How to set random id for dynamic created textbox and div.i have to set different id for dynamic created div and textbox.please give id for randomly
my code is here
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" />' +
'<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
</script>
</head>
<body>
<form id="Form2" runat="server">
<input id="btnAdd" type="button" value="Add Text" onclick="AddTextBox()" />
<br />
<br />
<div id="TextBoxContainer">
</div>
</form>
<script type="text/javascript">
var randomId = 0;
function GetDynamicTextBox(value) {
var newRandomIdOfTextBox = "dynamicTextBox" + randomId++ + "";
return '<input name = "DynamicTextBox" type="text" id="' + newRandomIdOfTextBox +'" />' +
'<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
</script>
randomId starts from 0 and every time you add a new text box it will increment by one making it unique..
you can set id ="'sometext'+Math.random();"
Please let me know if this helps

Cant access asp labels properties using c# in aspx page

I am trying to access an asp label field properties from c# code, and it keeps giving me the error:
The name 'lblTest' does not exist in the current context.
This is happening on my login.aspx page when calling the 'ValidateEmail' method.
There are no associated .cs files, just a login.master page.
I have a business request requiring me to modify someone elses code for enhancement, and I am guessing this has something to do with the existing content structure of .
I have tried placing this in master file, outside of the structure, etc. Still no joy.
Here is the login.aspx code:
<%# Page Language="C#" MasterPageFile="~/Masters/Login.master" AutoEventWireup="true" Culture="auto" UICulture="auto" EnableEventValidation="false" %>
<%# Import Namespace="Internal.Platform.Diagnostics" %>
<%# Import Namespace="Internal.Web" %>
<%# Import Namespace="Internal.Trial" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls.ScriptResourceProvider" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Trial" Namespace="Internal.Trial" TagPrefix="InternalTrial" %>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolderArea">
<script type="text/javascript">
</script>
<asp:Label ID="lblTest" runat="server"></asp:Label>
<asp:Login ID="intLogin" runat="server" DestinationPageUrl="Default.aspx"
OnPreRender="PreRender" Font-Names="Arial,Verdana,Sans-sarif" Font-Size="0.8em"
ForeColor="#000000">
<LayoutTemplate>
<div id="logoContainer">
<div class="logo"><img src="images/icons/logo.png" width="680" height="100"></div>
</div>
<div id="logonContainer">
<div>
<div class="LoginBtn1" onclick="lgnUser('pam')">Admin - Pam</div>
<div class="User1"><img src="images/icons/user1.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('lee')">Sales - Lee</div>
<div class="User2"><img src="images/icons/user2.png" width="80" height="80"></div>
</div>
<div>
<div class="LoginBtn1" onclick="lgnUser('samantha')">Support - Samantha</div>
<div class="User1"><img src="images/icons/user3.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('larry')">Marketing - Larry</div>
<div class="User2"><img src="images/icons/user4.png" width="80" height="80"></div>
</div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1"
OnServerValidate="ValidateEmail" ValidationGroup="ValidateGp"
ErrorMessage="This is a custom error validator" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ValidateGp"/>
<%-- These are hidden controls used for the login process --%>
<asp:TextBox ID="UserName" runat="server" style="display: none;"></asp:TextBox>
<asp:CustomValidator ID="UserNameRequired" ValidateEmptyText="True" OnServerValidate="ValidateUserName"
ClientValidationFunction="" runat="server" ControlToValidate="UserName" ErrorMessage="<%$ resources: UserNameRequired %>"
ToolTip="<%$ resources: UserNameRequired %>" ValidationGroup="intLogin" Text="<%$ resources: asterisk %>"></asp:CustomValidator>
<asp:TextBox ID="Password" runat="server" TextMode="Password" style="display: none;"></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" CommandName="Login" style="display: none;" ValidationGroup="intLogin" />
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</LayoutTemplate>
</asp:Login>
</asp:Content>
<script type="text/C#" runat="server">
private const string AuthError = "AuthError";
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
protected new void PreRender(object sender, EventArgs e)
{
object msg = Internal.Platform.Application.ApplicationContext.Current.State[AuthError];
if (msg == null)
{
var pageId = Internal.Platform.Application.ApplicationContext.Current.State["CurrentPageID"];
var key = pageId + ":" + AuthError;
msg = Internal.Platform.Application.ApplicationContext.Current.State[key];
}
if (msg != null)
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
Literal FailureText = (Literal)intLogin.FindControl("FailureText");
FailureText.Text = msg.ToString();
}
}
private static void SetAuthError(string errorMsg)
{
if (!string.IsNullOrEmpty(errorMsg))
{
Internal.Platform.Application.ApplicationContext.Current.State[AuthError] = errorMsg;
}
else
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
}
}
protected void ValidateUserName(object source, ServerValidateEventArgs args)
{
var oValidator = (CustomValidator)source;
if (oValidator == null)
{
args.IsValid = false;
SetAuthError(GetLocalResourceObject("InvalidUserNameValidation").ToString());
return;
}
char cBadChar;
BusinessRuleHelper.InvalidUserNameReason reason;
if (BusinessRuleHelper.IsValidUserNameValue(args.Value, out reason, out cBadChar))
{
args.IsValid = true;
SetAuthError(null);
}
else
{
args.IsValid = false;
switch (reason)
{
case BusinessRuleHelper.InvalidUserNameReason.NullOrEmpty:
case BusinessRuleHelper.InvalidUserNameReason.WhiteSpace:
oValidator.ErrorMessage = GetLocalResourceObject("UserNameRequired").ToString();
break;
default:
oValidator.ErrorMessage = GetLocalResourceObject("intLoginResource1.FailureText").ToString();
break;
}
SetAuthError(oValidator.ErrorMessage);
}
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
if (Internal.Trial.TrialLogin.VerifyEmail(args.Value.ToString()))
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
args.IsValid = true;
}
}
protected void Page_Error(Object sender, EventArgs e)
{
var userName = (TextBox)intLogin.Controls[0].FindControl("UserName");
string usrnm = userName.Text;
Exception err = Server.GetLastError();
if (err is Internal.Platform.Application.ValidationException)
{
string errMsg = err.Message;
}
}
</script>
Here is the login.master code:
<%# Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Internal.Platform.TimeZones tzs = new Internal.Platform.TimeZones();
Internal.Platform.TimeZone tz = tzs.CurrentTimeZone;
if (Request.Params["tz_info"] != null)
{
string[] tzinfo = Request.Params["tz_info"].Split(',');
if (tzinfo.Length == 11)
{
tz = tzs.FindTimeZone(tzinfo[0], tzinfo[1], tzinfo[2], tzinfo[3], tzinfo[4], tzinfo[5], tzinfo[6], tzinfo[7], tzinfo[8], tzinfo[9], tzinfo[10]);
}
}
else
{
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Warn("TimeZone: Unable to get timezone from client, using server timezone.");
}
Internal.Platform.Application.IContextService context = Internal.Platform.Application.ApplicationContext.Current.Services.Get<Internal.Platform.Application.IContextService>(true);
context.SetContext("TimeZone", tz);
}
Page.Title = GetLocalResourceObject("LoginPageTitle").ToString();
}
</script>
<script type="text/javascript">
function internalCleanUrl(strUrl) {
if(window.location.href.indexOf("internalclient") > -1) {
strUrl = strUrl;
} else {
strUrl = "internalClient" + "/" + strUrl;
}
return strUrl;
};
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Saleslogix</title>
<link type="text/css" href="../css/internalBase.css" rel="stylesheet" />
<link type="text/css" href="../css/BDLogin.css" rel="stylesheet" />
<style type="text/css">
body {
background-color : #f1f1f1;
background-image: none;
}
</style>
<script pin="pin" type="text/javascript">
var dojoConfig = {
parseOnLoad: true,
async: true,
isDebug: false,
locale: '<%= Global.Locale %>',
paths: { 'Internal.: '../../../jscript/Internal. },
deferredOnError: function (e) {
if (dojo.config.isDebug) {
}
}
};
</script>
<script pin="pin" type="text/javascript" src="javascript:internalCleanUrl("Libraries/dojo/dojo/dojo.js">)"</script>
</head>
<body>
<script pin="pin" src="Libraries/jQuery/jquery.js" type="text/javascript"></script>
<script pin="pin" src="jscript/BDLogin.js" type="text/javascript"></script>
<script pin="pin" src="jscript/timezone.js" type="text/javascript"></script>
<script pin="pin" src="jscript/Internal.platform/gears_init.js" type="text/javascript"></script>
<form id="Form1" runat="server" method="post" >
<div class="LoginArea" id="LoginContainer">
<asp:ContentPlaceHolder ID="ContentPlaceHolderArea" runat="server"></asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
If you have a login.designer.cs file try to regenerate it (delete and then click on project and chose 'convert to web application').
Try this:
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Import Namespace="System" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.UI" %>
<%# Import Namespace="System.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/C#" runat="server">
protected void btnTest_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:Button runat="server" ID="btnTest" OnClick="btnTest_Click" Text="test" />
</div>
</form>
</body>
</html>

Jquery datepicker - only every second click event fires

I have a page with a jqueryui datepicker control.
On each day selection, I post with ajax to a web method to do some server side data population to fill the drop down box which is beneath the calendar control.
I used this code for two pages already, first works perfect, but am having issues with this one.
The first time I select a date, the event fires fine, second time nothing happens, then the next click works fine again. So the event only fires on every second click, be it the same date or a different date.
I added an input control to capture date selection, which works fine on each select.
What bugs me now is, If I add an alert inside my select jquery function, it fires every time, take it out and I have this issue again.
Thanks
Markup:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="Site.Master" CodeBehind="calendartest.aspx.cs" Inherits="Test.calendartest" EnableEventValidation="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(function() {
$('#datepicker').datepicker({
onSelect: function(dateStr, inst) {
document.getElementById('<%= hSelectedDate.ClientID %>').value = dateStr;
var hubid = 2;
$('#<%=ddlAvailableTimes.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax
({
type: "POST",
url: "UserCP.aspx/PopulateAvailableTimeSlots",
data: ("{date:'" + dateStr + "', hubid:'" + hubid + "'}"),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnTimeSlotsPopulated
});
$("#datepicker_value").val(dateStr);
}
});
});
function OnTimeSlotsPopulated(response) {
PopulateControl(response.d, $("#<%=ddlAvailableTimes.ClientID %>"));
}
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">--Select Time Slot--</option>');
$.each(list, function() {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
$("#<%=ddlAvailableTimes.ClientID%>").attr("disabled", "disabled");
control.empty().append('<option selected="selected" value="0">--No Slots Available--<option>');
}
}
</script>
<input id="hSelectedDate" type="hidden" value="" runat="server" />
<input id="hfHub" type="hidden" value="" runat="server" />
<table style="width: 290px" cellpadding="0" cellspacing="0"
align="center">
<tr>
<td align="center">
<div id="datepicker">
</div>
<asp:DropDownList ID="ddlAvailableTimes" runat="server" Width="192px" Enabled="false">
<asp:ListItem Text="--Select Time Slot--" Value="0"></asp:ListItem>
</asp:DropDownList>
<input id="datepicker_value" />
</td>
</tr>
</table>
</asp:Content>
Server Side:
public partial class calendartest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static ArrayList PopulateAvailableTimeSlots(string date, string hubid)
{
ArrayList list = new ArrayList();
//Do stuff here
return list;
}
}
HTML Output:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<link href="css/master.css" rel="stylesheet" type="text/css" />
<link href="themes/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<link href="themes/jquery-ui-1.8.20.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.datepicker.js"></script>
<title>Test</title>
</head>
<body>
<form name="aspnetForm" method="post" action="calendartest.aspx" id="aspnetForm">
<script type="text/javascript">
$(function() {
$('#datepicker').datepicker({
onSelect: function(dateStr, inst) {
document.getElementById('ctl00_MainContent_hSelectedDate').value = dateStr;
var hubid = 2;
$('#ctl00_MainContent_ddlAvailableTimes').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax
({
type: "POST",
url: "UserCP.aspx/PopulateAvailableTimeSlots",
data: ("{date:'" + dateStr + "', hubid:'" + hubid + "'}"),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnTimeSlotsPopulated
});
$("#datepicker_value").val(dateStr);
}
});
});
function OnTimeSlotsPopulated(response) {
PopulateControl(response.d, $("#ctl00_MainContent_ddlAvailableTimes"));
}
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">--Select Time Slot--</option>');
$.each(list, function() {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
$("#ctl00_MainContent_ddlAvailableTimes").attr("disabled", "disabled");
control.empty().append('<option selected="selected" value="0">--No Slots Available--<option>');
}
}
</script>
<input name="ctl00$MainContent$hSelectedDate" type="hidden" id="ctl00_MainContent_hSelectedDate" />
<input name="ctl00$MainContent$hfHub" type="hidden" id="ctl00_MainContent_hfHub" />
<table style="width: 290px" cellpadding="0" cellspacing="0" align="center">
<tr>
<td align="center">
<div id="datepicker">
</div>
<select name="ctl00$MainContent$ddlAvailableTimes" id="ctl00_MainContent_ddlAvailableTimes" disabled="disabled" style="width:192px;">
<option selected="selected" value="0">--Select Time Slot--</option>
</select>
<input id="datepicker_value" />
</td>
</tr>
</table>
</form>
</body>
</html>

Categories