I'm working with selenium chromedriver. So far I have been able to log on, check a check box, navigate to another web page. I've hit a brick wall though when I get to the upload file page.
The form has 4 or 5 buttons that will open up a dialog box to pick a file off of the local hard drive. There is no input to put in directly. I think that when you click one of the buttons it executes a javascript function that choose a file.
Please look at the source code of this page and see if you have any ideas how to accomplish this:
^^^`enter code here<head><link rel="shortcut icon" href="/favicon.ico"/><title>NYWB-ECF v10.5.2 NextGen Production Database</title>
<script type="text/javascript">document.cookie = "PRTYPE=aty; path=/;"</script> <script>var default_base_path = "/"; </script> <link rel="stylesheet" type="text/css" href="/css/default.css"><script type="text/javascript" src="/lib/core.js"></script><script type="text/javascript" src="/lib/autocomplete.js"></script><script type="text/javascript" src="/lib/DisableAJTALinks.js"></script><script type="text/javascript">if (top!=self) {top.location.replace(location.href);}</script><script>var default_base_path = "/"; </script></head><body BGCOLOR=ffffff TEXT=000000 onLoad='SetFocus()'>
<div class="noprint">
<div id="topmenu" class="yuimenubar"><div class="bd">
<img id="cmecfLogo" class="cmecfLogo" src="/graphics/logo-cmecf-sm.png" alt="CM/ECF" title="" />
<ul class="first-of-type">
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?BankruptcyEvents&id=492888'>Ban</u>kruptcy <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?AdversaryEvents&id=492888'>A</u>dversary <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/iquery.pl'>Q</u>uery</a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?Reports&id=492888'>R</u>eports <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='/cgi-bin/DisplayMenu.pl?Utilities&id=492888'>U</u>tilities <div class='spritedownarrow'></div></a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" href='javascript: CMECF.MainMenu.searchPrompt();'>Searc</u>h</a></li>
<li class="yuimenubaritem" ><a class="yuimenubaritemlabel" onClick="CMECF.MainMenu.showHelpPage(''); return false">Help</a></li>
<li class="yuimenubaritem"><a class="yuimenubaritemlabel" href='/cgi-bin/login.pl?logout'>Log Out</a></li><li class='yuimenubaritem' id='placeholderForAlertsIcon'></li>
</ul></div>
<hr class="hrmenuseparator"></div></div>
<script type="text/javascript">
callCreateMenu=function(){
var fn = "CMECF.MainMenu.renderSimpleMenu";
if(typeof CMECF.MainMenu.renderSimpleMenu == 'function') {
CMECF.MainMenu.renderSimpleMenu();
}
}
if (navigator.appVersion.indexOf("MSIE")==-1){window.setTimeout( function(){ callCreateMenu(); }, 1);}else{CMECF.util.Event.addListener(window, "load", callCreateMenu());}</script> <div id="cmecfMainContent"><input type="hidden" id="cmecfMainContentScroll" value="0"><SCRIPT LANGUAGE="JavaScript">
var IsForm = false;
var FirstField;
function SetFocus() {
if(IsForm) {
if(FirstField) {
var ind = FirstField.indexOf('document.',0);
if(ind == 0)
{
eval(FirstField);
}
else
{
var Code = "document.forms[0]."+FirstField+".focus();";
eval(Code);
}
} else {
var Cnt = 0;
while(document.forms[0].elements[Cnt] != null) {
try {
if(document.forms[0].elements[Cnt].type != "hidden" &&
!document.forms[0].elements[Cnt].disabled &&
!document.forms[0].elements[Cnt].readOnly) {
document.forms[0].elements[Cnt].focus();
break;
}
}
catch(e) {}
Cnt += 1;
}
}
}
return(true);
}
</SCRIPT>
<div id="main-page-title" style="margin-bottom: .5em">
<font face="arial,helvetica" color="0000cc" size="4"><b><span id="main-page-title-content">Open New Bankruptcy Case</span></b></font>
</div> <FORM ENCTYPE='multipart/form-data' method=POST action="/cgi-bin/Dispatch.pl?127734820136425">
<!-ShowPage(CaseUpLoad.htm)->
<!-- RPM Packages: ao-bkecf-web-* -->
<!-- RPM Permissions: 444 -->
<!-- RPM Owner: nobody -->
<!-- RPM Group: nobody -->
<!-- RPM Flags: configure -->
<script src="/lib/CommonLib.js" language="Javascript"></script>
<SCRIPT LANGUAGE="JavaScript">
function CheckCreditorMatrix(input,lower,upper,field) {
var strng = "" + input;
var len = strng.length;
if (len < lower || len > upper) {
var msg = "The List of Creditors is empty or does not exist";
alert(msg);
if (field) {
field.focus();
field.select();
}
return 0;
} else if (len == 0) { return 2; }
else return 1;
}
</script>
<table cellpadding="5"><tr>
<td><b>Case information</b><br/>
<input name="case_1" type="file" size="40" />
<font size = "-1">c:\Debtor.txt</font>
</td>
</tr><tr>
<td><b>Petition</b><br/>
<input name="file_1" type="file" size="40" />
<font size = "-1">c:\Petition.pdf</font>
</td>
</tr><tr>
<td><b>List of creditors</b><br/>
<input name = "creditorMatrixFilename" type="hidden" />
<input name="file_1_MTX" type="file" size="40" onChange="document.forms[0].creditorMatrixFilename.value = this.value"/>
<font size = "-1">c:\Creditor.txt</font>
</td>
<script>
var numEvents = 1;
// record the names so we know if the user tried to upload a file, even if it is invalid
function AssignHiddenValues() {
document.forms[0].creditorMatrixFilename.value = document.forms[0].file_1_MTX.value;
for (var i = 0; i <= numEvents; i++) {
if(document.forms[0]["configured_file_"+i])
document.forms[0]["configured_filename_"+i].value = document.forms[0]["configured_file_"+i].value;
}
return 1;
}
</script>
</tr><tr>
<td><b>Chapter 13 plan (<em>chapter 13 only</em>)</b><br/>
<input name = "configured_filename_0" type="hidden" />
<input name="configured_file_0" type="file" size="40"
onChange="document.forms[0].configured_filename_0.value = this.value" />
<font size = "-1">c:\Plan.pdf</font>
</td>
</tr><tr>
<td><b>Certificate of credit counseling </b><br/>
<input name = "configured_filename_1" type="hidden" />
<input name="configured_file_1" type="file" size="40"
onChange="document.forms[0].configured_filename_1.value = this.value" />
<font size = "-1">c:\CCC.pdf</font>
</td>
</tr></table>
<script>numEvents = 2</script>
<SCRIPT LANGUAGE="JavaScript">
document.cookie = "DPFFuncs='CaseUpLoadCollectCaseInfo-'; path=/; |";
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
var timerId;
var BeenHere = 0;
IsForm = true;
function empty(s) {
var whitespace = " \ \
\
";
if(s == null || s.length == 0) {
return(true);
}
// Is s only whitespace characters?
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (whitespace.indexOf(c) == -1) return false;
}
return(true);
}
function ClearTimer() {
BeenHere = 0;
clearTimeout(timerId);
return(true);
}
var FormId = 0;
function ProcessForm() {
if(BeenHere == 1) {
return(false);
}
if( ! AssignHiddenValues() ) {return false}
if( ! CheckString(document.forms[0].case_1.value, 1, 1000, document.forms[0].case_1) ) {return false}
if( ! CheckString(document.forms[0].file_1.value, 1, 1000, document.forms[0].file_1) ) {return false}
if( ! CheckCreditorMatrix(document.forms[0].file_1_MTX.value, 1, 1000, document.forms[0].file_1_MTX) ) {return false}
BeenHere = 1;timerId=setTimeout("ClearTimer()",5000);document.forms[FormId].submit();return true }
function RunAfterClear() {
}
</SCRIPT>
<TABLE><TR> <TD><INPUT NAME="button1" Value='Next' TYPE= "button" ONCLICK="ProcessForm()" > <TD> <TD> <INPUT NAME="reset" TYPE="RESET" VALUE="Clear" onClick="setTimeout('RunAfterClear()',100)"></TD> </TR></TABLE></FORM></div></body></html>
}
You can click the choose file button , and use sendkeys to give your location of the file.
WebElement upload = driver.findElement(By.linkText("Upload a Document:( .tex, .txt, .doc, .docx, .odt, .pdf, .rtf )"));
upload.sendKeys("C:\path\File.txt");
Checkout this code.
I need some help with some MVC stuff. I'm trying to update some legacy code I inherited, and am an absolute n00b with web stuff. This same exact code works on the installed version of the site, but will not work correctly here.
The Index.chtml file is:
#model QspAudits.Models.LoginModel
#{
Layout = null;
// Unimportant viewbag stuff. Can post if needed.
}
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Site | #ViewBag.Title</title>
#Styles.Render("http://hotline.rimg.net/qspaudits/Content/css/qsp.css")
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function submitenter(myfield, e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13) {
$("#FormLogin").submit();
return false;
}
else
return true;
}
$(document).ready(function () {
$('.login_btn').click(function () {
$(this).closest('form').submit();
});
});
</script>
</head>
<body id="#ViewBag.BodyID" class="#ViewBag.BodyClass">
#using (Html.BeginForm("Index", "Login", FormMethod.Post, new {id = "FormLogin"}))
{
<div id="loginBox" class="login">
<div class="loginForm">
<img alt="" src="#Url.Content("~/Images/samsclub_medlogo.png")" class="identity"/>
<h2>#ViewBag.Site</h2>
<label>Login</label>
#Html.TextBoxFor(x => x.username, new { #class = "TextBox", #autofocus=""})
<label>Password</label>
#Html.PasswordFor(x => x.password, new { #class = "PasswordBox", #onkeypress = "return submitenter(this,event)" })
<div id="login_btn" class="login_btn"></div> <span>#Model.message</span>
</div>
</div>
}
</body>
</html>
The LoginController.cs looks like:
namespace QspAudits.Controllers
{
public class LoginController : Controller
{
private QspAuditsEntities db = new QspAuditsEntities();
private BT8_GCEntities bt_db = new BT8_GCEntities();
[HttpGet]
[AllowAnonymous]
public ActionResult Index()
{
ViewBag.bodyID = "login";
LoginModel log = new LoginModel();
log.message = "";
return View(log);
}
[HttpPost]
[AllowAnonymous]
public ActionResult Index(LoginModel formResult)
{
UserLogin_Result log = db.UserLogin(formResult.username).FirstOrDefault();
if (log != null && formResult.password != null)
{
int pass;
if (Int32.TryParse(log.password.ToString(), out pass) == true || log.validation == 1)
{
int dbPass = (log.validation == 3 ? pass : Common.MD5Hash(formResult.password));
if (dbPass == (int)log.password) //use real valid code
{
FormsAuthentication.SetAuthCookie(log.user_id.ToString() + "|" + log.full_name + "|" + (log.validation == 1 ? "1" : "3"), false);
return RedirectToAction("Index", "Home");
}
}
}
formResult.password = "";
formResult.message = "Incorrect Username/Password";
return View(formResult);
}
public ActionResult SignOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Login");
}
}
}
When I run the code to test (through VS2012), the only breakpoint that ever gets hit is in the [HttpGet] block. The strangeness is that it hits the [HttpGet] block breakpoint twice. The [HttpPost] block never gets touched.
This code is running on the live server, so it's got to be something stupid simple I'm missing.
I have a custom asp.net server component that is rendered as below:
<div id="divContentRating">
<div id="divAskForRating">
#Question
<br />
<a id="likeIcon"><img src="#PositiveRateIconPath"/></a>
<a id="neutralIcon"><img src="#NeutralRateIconPath"/></a>
<a id="unlikeIcon"><img src="#NegativeRateIconPath"/></a>
</div>
<div id="divPositiveRating">
<div>
<img src="#PositiveRateIconPath"/> #PositiveAnswerMessage <br />
Güncelle
</div>
</div>
<div id="divNegativeRating">
<div>
<img src="#NegativeRateIconPath"/> #NegativeAnswerMessage <br />
Güncelle
</div>
</div>
<div id="divNeutralRating">
<div>
<img src="#NeutralRateIconPath"/> #NeutralAnswerMessage <br />
Güncelle
</div>
</div>
<input type="hidden" id="HasRated" value="#HasRated">
<input type="hidden" id="Rate" value="#Rate">
<input type="hidden" id="ContentKey" value="#ContentKey">
<input type="hidden" id="RatingId" value="#RatingId">
</div>
Is it possible to handle the click on the images in my web control? I mean, I want to do some operations when user clicks on the images, but I want to code these in my web control.
Here is my web control:
[DefaultProperty("ContentKey")]
[ToolboxData("<{0}:ContentRating runat=server></{0}:ContentRating>")]
public class ContentRating : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string ContentKey
{
get
{
String s = (String)ViewState["ContentKey"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["ContentKey"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string PositiveRateIconPath
{
get
{
String s = (String)ViewState["PositiveRateIconPath"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["PositiveRateIconPath"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string NegativeRateIconPath
{
get
{
String s = (String)ViewState["NegativeRateIconPath"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["NegativeRateIconPath"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string NeutralRateIconPath
{
get
{
String s = (String)ViewState["NeutralRateIconPath"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["NeutralRateIconPath"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
ContentRatingSettings contentRatingSettings = GetContentRatingSettings(this.ContentKey);
if (!contentRatingSettings.Visible)
{
output.Write(string.Empty);
return;
}
StringBuilder builder = new StringBuilder(#"
<div id=""divContentRating"">
<div id=""divAskForRating"">#Question
<br />
<a id=""likeIcon""><img src=""#PositiveRateIconPath""/></a>
<a id=""neutralIcon""><img src=""#NeutralRateIconPath""/></a>
<a id=""unlikeIcon""><img src=""#NegativeRateIconPath""/></a>
</div>
<div id=""divPositiveRating"">
<div>
<img src=""#PositiveRateIconPath""/> #PositiveAnswerMessage <br />
Güncelle
</div>
</div>
<div id=""divNegativeRating"">
<div>
<img src=""#NegativeRateIconPath""/> #NegativeAnswerMessage <br />
Güncelle
</div>
</div>
<div id=""divNeutralRating"">
<div>
<img src=""#NeutralRateIconPath""/> #NeutralAnswerMessage <br />
Güncelle
</div>
</div>
<input type=""hidden"" id=""HasRated"" value=""#HasRated"">
<input type=""hidden"" id=""Rate"" value=""#Rate"">
<input type=""hidden"" id=""ContentKey"" value=""#ContentKey"">
<input type=""hidden"" id=""RatingId"" value=""#RatingId"">
<script type=""text/javascript"">
$(document).ready(function () {
var protocol = location.protocol;
var host = window.location.host;
if ($(""#HasRated"").val() == ""True"")
{
var rate = $(""#Rate"").val();
if (rate == 1) {
setPositiveRatedView();
}
else if (rate == 0) {
setNeutralRatedView();
}
else if (rate == -1) {
setNegativeRatedView();
}
else {
setNotRatedView();
}
}
else {
setNotRatedView();
}
$(""#likeIcon"").click(function () {
alert(""like"");
setPositiveRatedView();
ratePage(1, """");
});
$(""#neutralIcon"").click(function () {
alert(""neutral"");
setNeutralRatedView();
ratePage(0, """");
});
$(""#unlikeIcon"").click(function () {
alert(""unlike"");
setNegativeRatedView();
//mkMPopClc('NegativeRatingReason', 200, 300, 0, 0);
});
$("".updateRate"").click(function () {
setNotRatedView();
});
function setNotRatedView() {
$(""#divNeutralRating"").fadeOut();
$(""#divPositiveRating"").fadeOut();
$(""#divAskForRating"").fadeIn();
$(""#divNegativeRating"").fadeOut();
}
function setPositiveRatedView()
{
$(""#divNegativeRating"").fadeOut();
$(""#divNeutralRating"").fadeOut();
$(""#divAskForRating"").fadeOut();
$(""#divPositiveRating"").fadeIn();
}
function setNegativeRatedView() {
$(""#divNeutralRating"").fadeOut();
$(""#divPositiveRating"").fadeOut();
$(""#divAskForRating"").fadeOut();
$(""#divNegativeRating"").fadeIn();
}
function setNeutralRatedView() {
$(""#divNegativeRating"").fadeOut();
$(""#divPositiveRating"").fadeOut();
$(""#divAskForRating"").fadeOut();
$(""#divNeutralRating"").fadeIn();
}
function ratePage(rating, comment)
{
//alert(rating + """" """" + comment);
var contentKey = $(""#ContentKey"").val();
var hasRated = $(""#HasRated"").val();
var ratingId = $(""#RatingId"").val();
}
});
</script>
</div>");
SetTrackingCookie();
builder.Replace("#ContentKey", this.ContentKey);
builder.Replace("#PositiveRateIconPath", this.PositiveRateIconPath);
builder.Replace("#NeutralRateIconPath", this.NeutralRateIconPath);
builder.Replace("#NegativeRateIconPath", this.NegativeRateIconPath);
builder.Replace("#Question", contentRatingSettings.Question);
builder.Replace("#PositiveAnswerMessage", contentRatingSettings.PositiveAnswerMessage);
builder.Replace("#NeutralAnswerMessage", contentRatingSettings.NeutralAnswerMessage);
builder.Replace("#NegativeAnswerMessage", contentRatingSettings.NegativeAnswerMessage);
output.Write(builder);
}
}
Thanks in advance,
If you want to attach events to controls, overriding CompositeControl will be a lot easier than WebControl.
CreateChildControl can route the event to its child but WebControl can't.
Please keep it mind that it is an alternative approach to your question because it requires some of changes (from your original code).
Depending on what you want to do, the quickest option will be to add runat="server" tag to the image control along with an on click event handler than points to a function.
This will perform a postback to the asp page whenever the image is clicked.
If the post back is not desired then you will need to wire up javascript to do an ajax based postback and appropriate client/server handlers.
I am trying to post the value of the textbox and have that same value posted on the page in the "You said..." section.
My TypeScript/JavaScript is:
declare var document;
declare var xmlhttp;
window.onload = () => {
start();
};
function sayHello(msg: any) {
// Post to server.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// All right - data is stored in xhr.responseText
alert("done" + " " + xmlhttp.responseText);
}
else {
// Server responded with a status code.
alert("error");
}
}
}
xmlhttp.open("POST", "Default.cshtml");
xmlhttp.send("someValue=" + msg);
return msg;
}
function start() {
// Add event Listeners for user interaction
var element = document.getElementById("link");
element.addEventListener("click", function () {
var tb = (<HTMLInputElement>document.getElementById("tbox"));
var element = document.getElementById("response")
.innerText = sayHello(tb.value);
}, false);
// Setup XMLHttpRequests (AJAX)
if (XMLHttpRequest) {
// Somewhat cross-browser
xmlhttp = new XMLHttpRequest();
}
else {
// Legacy IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
And the HTML is (this page is Default.cshtml):
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Home Page";
var msg = Request["someValue"];
}
<h1>TypeScript HTML App</h1>
<div id="content">
Say Hello:
<br />
<input type="text" value="dfgdfgdfg" id="tbox" />
<br />
<p id="response">awaiting a response.</p>
<br />
<p>You said:<br />
#msg</p>
</div>
And I've included all references properly:
<script src="~/App.js"></script>
The response code I get back is 200.
Am I doing something wrong here? I've followed many tutorials, docs and so forth, and I just don't see what I'm doing wrong. It looks practically identical.
When you are processing an XMLHttpRequest as a POST, you need to add a couple of extra headers - add them before you call send, like this:
var params = "someValue=" + encodeURIComponent(msg);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length.toString());
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
UPDATE - My Full Example
Default.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
Page.Title = "Home Page";
var msg = Request["someValue"];
}
#if (msg != null) {
Layout = null;
<text>You said #msg</text>
} else {
<h1>TypeScript HTML App</h1>
<div id="content">
Say Hello:
<br />
<input type="text" value="dfgdfgdfg" id="tbox" />
<br />
<p id="response">awaiting a response.</p>
</div>
}
App.ts
declare var document;
declare var xmlhttp: XMLHttpRequest;
window.onload = () => {
start();
};
function sayHello(msg: any) {
// Post to server.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// All right - data is stored in xhr.responseText
//alert("done" + " " + xmlhttp.responseText);
document.getElementById("response").innerText = xmlhttp.responseText;
}
else {
// Server responded with a status code.
alert("error");
}
}
}
var params = "someValue=" + encodeURIComponent(msg);
xmlhttp.open("POST", "");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length.toString());
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return msg;
}
function start() {
// Add event Listeners for user interaction
var element = document.getElementById("link");
element.addEventListener("click", function () {
var tb = <HTMLInputElement>document.getElementById("tbox");
sayHello(tb.value);
}, false);
// Setup XMLHttpRequests (AJAX)
if (XMLHttpRequest) {
// Somewhat cross-browser
xmlhttp = new XMLHttpRequest();
}
else {
// Legacy IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
Can you try replacing:
xmlhttp.send("someValue" + msg);
with
xmlhttp.send("someValue=" + msg);
I hope this helps. As stated I am a bit confused by your flow, but it might still help you.
PageA.cshtml (the page that houses the javascript)
<h1>TypeScript HTML App</h1>
<div id="content">
Say Hello:
<br />
<input type="text" value="dfgdfgdfg" id="tbox" />
<br />
<p id="response">awaiting a response.</p>
</div>
<script src="app.js" type="text/javascript"></script>
PageB.cshtml (the page we request via ajax call)
#{
var msg = Request["someValue"];
}
<p>You said:<br />
#msg</p>
App.js (javascript file running on page A and requesting page B)
declare var document;
declare var xmlhttp;
window.onload = () => {
start();
};
function sayHello(msg: any, callback) {
// Post to server.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// alert(xmlhttp.responseText);
} else {
// Server responded with a status code.
alert("error");
}
}
};
xmlhttp.open("POST", "PageB.cshtml");
xmlhttp.send("someValue=" + msg);
}
function start() {
// Add event Listeners for user interaction
var element = document.getElementById("link");
element.addEventListener("click", function () {
var tb = (<HTMLInputElement>document.getElementById("tbox"));
sayHello(tb.value);
document.getElementById("response")
.innerHTML = tb.value;
}, false);
// Setup XMLHttpRequests (AJAX)
if (XMLHttpRequest) {
// Somewhat cross-browser
xmlhttp = new XMLHttpRequest();
}
else {
// Legacy IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
What I am doing is making a request from PageA to PageB. Then reading the result I manipulate the dom of PageA to contain the markup received from PageB. This markup contains the message passed along with the request.
Is this the flow you are trying to achieve?
I wrote a google map lookup page. Everthing worked fine until I referenced the page to use a master page. I removed the form tag from the master page as the search button on the map page is a submit button. Everything else on my page appears but the google map div appears with map navigation controls and logo but no map visuals appear.
I retested with the previous, non master page version and the map appears correctly. Any thoughts on what I'm missing?
Please view below Code and let me know its useful ...
MasterPage Code ( GMap.master page)
< body onload="initialize()" onunload="GUnload()" >
< form id="form1" runat="server" >
< div >
< asp:contentplaceholder id="ContentPlaceHolder1" runat="server" >
< /asp:contentplaceholder >
< /div >
< /form >
< /body >
GMatTest.aspx Page which is used GMap.Master page
< %# Page Language="C#" MasterPageFile="~/MasterPages/GMap.master" AutoEventWireup="true"
CodeFile="GMapTest.aspx.cs" Inherits="GMapTest" Title="Google Map Page" % >
< asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server" >
< script src="http://maps.google.com/maps?file=api&v=2&key=< % = AppConfig.GoogleMapApiKey % >"
type="text/javascript" >< /script >
< script type="text/javascript" >
var map = null;
var geocoder = null;
var latsgn = 1;
var lgsgn = 1;
var zm = 0;
var marker = null;
function initialize()
{
if (GBrowserIsCompatible())
{
var latitude= "";
var longitude= "";
map = new GMap2(document.getElementById("map_canvas"));
var center = new GLatLng(0,0);
map.setCenter(center, 17);
map.addControl(new GLargeMapControl());
map.addControl(new GScaleControl());
map.enableScrollWheelZoom();
map.addControl(new GMapTypeControl());
map.enableDoubleClickZoom();
marker = new GMarker(center,{draggable: true});
geocoder = new GClientGeocoder();
GEvent.addListener(marker, "dragend", function() {
var point = marker.getLatLng();
marker.openInfoWindowHtml("Latitude: " + point.y + "< /br > Longitude: " + point.x );
});
GEvent.addListener(marker, "click", function() {
var point = marker.getLatLng();
});
map.addOverlay(marker);
GEvent.trigger(marker, "click");
if (latitude > 0 && longitude > 0)
{
}
else
{
showAddress();
}
}
}
Below porsion is continue so please copy it also
function showAddress()
{
var isAddressFound=false;
var companyAddress = '';
var address='satyam mall, vastrapur, ahmedabad, gujrat, india';
if (geocoder)
{
geocoder.getLatLng(address,function(point) {
if (!point) {
alert(address + " not found");
} else {
isAddressFound =true;
map.setCenter(point,17);
zm = 1;
marker.setPoint(point);
GEvent.trigger(marker, "click");
}
}
);
//If address not found then redirect to company address
if(!isAddressFound)
{
geocoder.getLatLng(companyAddress,
function(point) {
if (!point) {
} else {
isAddressFound =true;
map.setCenter(point,17);
zm = 1;
marker.setPoint(point);
GEvent.trigger(marker, "click");
}
}
);
}
}
}
< /script >
< div id="map_canvas" style="width: 100%; height: 425px" >
< /div >
< /asp:Content >
this is the code i used.it works fine here but whenever i add master page it does not perform any use functionality
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Find latitude and longitude with Google Maps</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAPkZq56tNYNmeuZjNQQ2p3hT0NZP-HbfQNNfWb9Z5SLbjZKYKwBTrGBqtttFmF2d-kWv2B2nqW_NyEQ"
type="text/javascript"></script>
<script type="text/javascript">
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var center = new GLatLng(48.89364, 2.33739);
map.setCenter(center, 15);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(6);
document.getElementById("lng").innerHTML = center.lng().toFixed(6);
GEvent.addListener(marker, "dragend", function() {
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(6);
document.getElementById("lng").innerHTML = point.lng().toFixed(6);
});
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(6);
document.getElementById("lng").innerHTML = center.lng().toFixed(6);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(6);
document.getElementById("lng").innerHTML = point.lng().toFixed(6);
});
});
}
}
function showAddress(address) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
document.getElementById("lat").innerHTML = point.lat().toFixed(6);
document.getElementById("lng").innerHTML = point.lng().toFixed(6);
map.clearOverlays()
map.setCenter(point, 14);
var marker = new GMarker(point, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
var pt = marker.getPoint();
map.panTo(pt);
document.getElementById("lat").innerHTML = pt.lat().toFixed(6);
document.getElementById("lng").innerHTML = pt.lng().toFixed(6);
});
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(6);
document.getElementById("lng").innerHTML = center.lng().toFixed(6);
GEvent.addListener(marker, "dragend", function() {
var pt = marker.getPoint();
map.panTo(pt);
document.getElementById("lat").innerHTML = pt.lat().toFixed(6);
document.getElementById("lng").innerHTML = pt.lng().toFixed(6);
});
});
}
}
);
}
}
</script>
</head>
<body onload="load()" onunload="GUnload()" >
<p>This page uses the Google Maps API to find out accurate geographical coordinates (latitude and longitude) for any place on Earth. <br/>It provides two ways to search, either by moving around the map and zooming in, or by typing an address if the place is unknown.<br/>
<i>
<p> The default location and address are those of Mondeca office in Paris.<br />
<p><b> Find coordinates by moving around the map</b></p> <p>1. Drag and drop the map to broad location. <br/>
2. Zoom in for greater accuracy. <br/>
3. Drag and drop the marker to pinpoint the place. The coordinates are refreshed at the end of each move. </p>
<form action="#" onsubmit="showAddress(this.address.value); return false">
<p>
<input type="text" size="60" name="address" value="3 cité Nollez Paris France" />
<input type="submit" value="Search!" />
</p>
</form>
<p align="left">
<table bgcolor="#FFFFCC" width="300">
<tr>
<td width="100"><b>Latitude</b></td>
<td id="lat"></td>
</tr>
<tr>
<td width="100"><b>Longitude</b></td>
<td id="lng"></td>
</tr>
</table>
</p>
<p>
<div align="center" id="map" style="width: 600px; height: 400px"><br/></div>
</p>
</body>
</html>
It was same problem as mentioned above. when I used master page no google map was drawn. I found solution later.
You need to call the Javascript function in .aspx page where you want to show google map (like initialize();) may be different in your case.
code in my case:
<script type="text/javascript"">
window.onload = function () {
DrawGoogleMap();
}
function DrawGoogleMap() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("GoogleMap_Div"));
geocoder = new GClientGeocoder();
GService.GetGoogleObject(fGetGoogleObject);
}
}
</script>
Load up FireFox and FireBug, start looking for javascript errors.
One item that I have found, you have to call setCenter on the map for it to display.
Also, if you are adding markers (or layers), you have to add the marker after you call setCenter.
Ended up having to force the div to visible
See this thread on google maps support forums:
http://groups.google.com/group/Google-Maps-Troubleshooting/browse_thread/thread/0d27b66eef5f5d9e/1259a2991412f796?lnk=raot
Thanks!!
One thing that can change when you add a master page is your elements ids.
If the div you are displaying the map in has runat="server" on it, you could have a problem.
You would add that tag so you could manipulate the div from code-behind.
So, if my div looks like this:
<div id="gmap" runat="server"></div>
If so, when you are initializing your map, you need to get the ClientId of the div. That would look like this:
var mapDiv = '<%= gmap.ClientID %>';
var map = new GMap2(mapDiv);
the code i used is
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<META NAME="AUTHOR" CONTENT="Rakshith Krishnappa">
<META NAME="DESCRIPTION" CONTENT="KML Tool - Get Latitude and Longitude for KML Polyline">
<META NAME="KEYWORDS" CONTENT="Google, maps, mashup, tools, kml, polyline">
<META NAME="ROBOTS" CONTENT="ALL">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title>Mapmash | Geocoder Tool | Geocode - Reverse Geocode - IP Geocode</title>
<%--<style type="text/css">
<!--
html {
height: 100%; width:100%;overflow:hidden;
}
body {
background-color: white;
font-family: Arial, sans-serif;
font-size:10pt
}
h1 {
font-size: 18pt;
}
#map {
height: 100%;
}
#hand_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Bsu.png);
}
#hand_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bsd.png);
}
#placemark_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Bmu.png);
}
#placemark_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bmd.png);
}
#line_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Blu.png);
}
#line_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bld.png);
}
#shape_b {
width:31px;
height:31px;
background-image: url(http://google.com/mapfiles/ms/t/Bpu.png);
}
#shape_b.selected {
background-image: url(http://google.com/mapfiles/ms/t/Bpd.png);
}
-->
</style>
<style type="text/css">
v\:* {
behavior:url(#default#VML);
}
</style>--%>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAPkZq56tNYNmeuZjNQQ2p3hT0NZP-HbfQNNfWb9Z5SLbjZKYKwBTrGBqtttFmF2d-kWv2B2nqW_NyEQ"></script>
<script type="text/javascript">
google.load("maps", "2");
</script>
<script src="dragzoom.js" type="text/javascript"></script>
<script src="http://adserver.lat49.com/lat49/v0.10/lat49.js" type="text/javascript"></script>
<!-- Start of Google Analytics Code -->
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2417064-1";
urchinTracker();
</script>
<!-- End of Google Analytics Code -->
<script type="text/javascript">
//<![CDATA[
//rakf1 modified code taken from these 2 sources: - http://www.gorissen.info/Pierre/maps/googleMapLocationv4.php and - Distance Measurement Tool - Google Mapplets
// argItems code taken from
// http://www.evolt.org/article/Javascript_to_Parse_URLs_in_the_Browser/17/14435/?format=print
var map;
var coordinates = '';
var geocoder = new GClientGeocoder();
var added = 0;
var marker;
function write_point() {
var position = marker.getPoint();
var lat = position.y.toFixed(6);
var lng = position.x.toFixed(6);
coordinates = lng + "," + lat + "\n";
document.getElementById("attribute").value = 'lat="'+lat+'" lng="'+lng+'"';
document.getElementById("latlng").value = '<lat>'+lat+'</lat>\n<lng>'+lng+'</lng>';
document.getElementById("kml").value = lng+','+lat;
document.getElementById("coord").value = marker.getPoint().toUrlValue();
}
function get_address1() {
GEvent.addListener(marker, "click", function(){
var position = marker.getPoint();
var lat = position.y.toFixed(6);
var lng = position.x.toFixed(6);
var html = 'FreeReverseGeo.com (~address):<br><iframe id="RSIFrame" name="RSIFrame" style="overflow:hidden; width:200px; height:55px; border: 1px" src="http://www.freereversegeo.com/gmap-api.php?lat_1=' + lat + '&lng_1=' + lng + '"></iframe><br>('+lat+','+lng+')';
marker.openInfoWindowHtml(html);
});
}
function get_address() {
GEvent.addListener(marker, "click", function(){
var position = marker.getPoint();
geocoder.getLocations(position, function(addresses) {
if(addresses.Status.code != 200) {
marker.openInfoWindowHtml("<b>Google Reverse Geocode:</b><br>Reverse geocoder failed to find an address for " + position.toUrlValue());
}
else {
address = addresses.Placemark[0];
var html = address.address;
marker.openInfoWindowHtml("<b>Google Reverse Geocode:</b><br>"+html);
}
});
});
}
function my_location() {
if (google.loader.ClientLocation) {
var cl = google.loader.ClientLocation;
var html = 'Google ClientLocation: <br><font size="+1">' + cl.address.city + ', ' + cl.address.region+ '<br> ' + cl.address.country+'</font><br>('+cl.latitude+','+cl.longitude+')';
var point = new GLatLng(cl.latitude, cl.longitude);
if(!marker) {
map.setZoom(12);
marker = new GMarker(point,{title: "Click to get address", draggable: true});
map.addOverlay(marker);
added = 1;
}
map.setCenter(point);
marker.setPoint(point);
marker.openInfoWindowHtml(html);
}
}
function draw_point() {
GEvent.addListener(map, 'click', function(overlay, point) {
if (point && !added) {
marker = new GMarker(point, {icon:G_DEFAULT_ICON, draggable: true, title: "Click to get address"});
map.addOverlay(marker);
added = 1;
GEvent.addListener(marker, "dragend", function(){
write_point();
});
}
else if (point && added) {
marker.setPoint(point);
}
write_point();
get_address();
});
}
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 11);
if(!marker) {
marker = new GMarker(point, {icon:G_DEFAULT_ICON, draggable: true, title: "Click to get address"});
map.addOverlay(marker);
get_address();
added = 1;
}
marker.setPoint(point);
write_point();
}
}
);
}
function showLat49Ads(){
Lat49.initAds(19);
var center = map.getCenter();
var lat = center.lat();
var lng = center.lng();
var zoomlevel = Lat49.Tile.convertGMap2Zoom(map.getZoom());
Lat49.updateAdByLatLon("lat49ads", lat, lng, zoomlevel);
}
function load(){
map = new GMap2(document.getElementById("map"),{draggableCursor: 'crosshair', draggingCursor: 'crosshair'});
map.addControl(new GSmallZoomControl());
map.addControl(new GMenuMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(61,7)));
map.addMapType(G_PHYSICAL_MAP);
map.addControl(new GOverviewMapControl());
var boxStyleOpts = { opacity: .2, border: "2px solid yellow" };
var otherOpts = {
buttonHTML: "<img src='zoom-control-inactive1.png' title='Drag Zoom' />",
buttonZoomingHTML: "<img src='zoom-control-active1.png' title='Drag Zoom: Cancel' />",
buttonStartingStyle: {width: '15px', height: '15px'},
overlayRemoveTime: 0 };
map.addControl(new DragZoomControl(boxStyleOpts, otherOpts, {}), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(25,7)));
map.setCenter(new GLatLng(37.35, -121.93), 12);
draw_point();
showLat49Ads();
GEvent.addListener(map, "moveend", showLat49Ads);
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<table width="100%" height="100%" style="width:100%; height:100%">
<tr style="vertical-align:top">
<td style="width:320px">
<table><tr>
</tr></table>
</td>
<td>
</td>
<td align="right">
<nobr>
<form action="#" onsubmit="showAddress(this.address.value); return false">
<input type="text" size="30" name="address" value="Chicago, IL" />
<input type="submit" value="Go!" />
</form>
</nobr>
</td>
</tr>
<tr>
<td valign="top">
<div style="width:300px;font-size:8pt"><h1>GeoCoder</h1>Click on the map or search a place to add a marker and drag marker around to get marker position coordinates. Click on marker to get approximate address.</div>
<br><span style="font-size:8pt"><b>Coordinates (lat, lng):</b> [for GLatLng]</span><br>
<input type="text" size="30" id="coord" onclick="this.select()"/>
<br><br><span style="font-size:8pt"><b>Coordinates (lng, lat):</b> [for KML]</span><br>
<input type="text" size="30" id="kml" onclick="this.select()"/>
<br><br><span style="font-size:8pt"><b>Coordinates (lat="x.xx" lng="x.xx"):</b></span><br>
<input type="text" size="30" id="attribute" onclick="this.select()"/>
<br><br><span style="font-size:8pt"><b>Coordinates (<lat> <lng>):</b></span><br>
<textarea rows="2" cols="24" id="latlng" onclick="this.select()" ></textarea>
<br>
<br>
<script type="text/javascript"><!--
google_ad_client = "pub-2773616400896769";
/* maptools_300x250_01 */
google_ad_slot = "1034665593";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</td>
<td colspan="2" width="100%" height="100%">
<div style="position:relative;width:100%;height:100%">
<div id="lat49ads" lat49adposition="top-right"
style="position:absolute;top:7px; right:4px; width:125px; height:133;z-index:99999;"></div>
<div id="map" style="width:100%;height:400px;min-height:400px;border:1px solid #999;"></div>
</div>
</td>
</tr>
</table>
</body>
</html>
if anyone have any idea regarding to code i posted earlier please post a comment.
thanks