Javascript not working with Ext.Net - c#

I am using Asp.net with Ext.Net framework. And I must use Javascript code (not ext.net code).
Default.aspx page:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="tıkla" ID="btnGetir" OnClick="btnGetir_Click" />
............
............
Default.aspx.cs page:
public void btnGetir_Click(object sender, EventArgs e)
{
String url = "http://blablablablabla:8080/MeramElektrik2/webresources/entities.layers/GetLayer/1004";
String html_sonuc;
WebResponse objResponse;
WebRequest objRequest = HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
html_sonuc = sr.ReadToEnd();
sr.Close();
}
////////////Script Çalıştırma Kodu///////////////////////////
ScriptManager.RegisterStartupScript(
this,
this.GetType(),
"deneme2",
"deserialize('" + html_sonuc + "');",
true);
/////////////////////////////////////////////////////////////
txtScript.Text = html_sonuc;
}
OpenLayerUsers.js page:
function deserialize(html_sonuc) { //GEOJSON I, ÇİZİLMİŞ ŞEKLE DÖNÜŞTÜRÜYOR
//var element = document.getElementById('txtScript');
var features = geojson.read(html_sonuc);
//var features = json.read(element.value);
var bounds;
if (features) {
if (features.constructor != Array) {
features = [features];
}
for (var i = 0; i < features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectors.addFeatures(features);
map.zoomToExtent(bounds);
var plural = (features.length > 1) ? 's' : '';
//element.value = features.length + ' feature' + plural + ' added'
} else {
//element.value = 'Bad input';
}
}
Result, deserialize(html_sonuc) function not working.

here is the simple test case
aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Js/jquery-1.8.2.min.js"></script>
<script>
Ext.onReady(function () {
});
function deserialize(testdt) {
alert('sonic bumm:' + testdt);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ext:ResourceManager ID="myrsc" runat="server"></ext:ResourceManager>
<div>
<asp:Button runat="server" Text="tıkla" ID="btnGetir" OnClick="btnGetir_Click" />
</div>
</form>
</body>
</html>
and the code behind;
protected void btnGetir_Click(object sender, EventArgs e)
{
// do something here
// and add the client script
string testdt = "testdata";
string script = "deserialize('" + testdt + "')";
myrsc.AddScript(script);
}

Related

DropDownList Not Visible After Selecting Item

I have an ASP DropDownList that disappears when an item is selected from it. What is supposed to happen is that another DropDownList is supposed to appear but it doesn't display either.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
<title>KYFB Black Book</title>
<link rel="stylesheet" href="blackbook.css" />
</head>
<body>
<img class="logo" src="images/logo.jpg"/>
<p id="home_title" runat="server">Black Book</p>
<form id="sign_in_form" runat="server">
<div>
<input id="username_field" runat="server" type="text" placeholder="Username" name="username" /> <br />
<input id="password_field" runat="server" type="password" placeholder="Password" name="password" /> <br /> <br />
<input id="submit_button" runat="server" type="submit" value="Sign In" onclick="ajaxFunction();" />
</div>
</form>
<form id="selection_form" runat="server">
<div id="counties_div" style="display: block; width: 15%; margin: auto;" runat="server">
<p id="county_list_title" style="color:white;" runat="server">Select a county</p>
<asp:DropDownList ID="county_list" AutoPostBack="True" OnSelectedIndexChanged="countyChange" runat="server"></asp:DropDownList>
<br />
<p id="committee_list_title" style="color:white;" runat="server">Select a committee</p>
<asp:DropDownList ID="committee_list" AutoPostBack="true" OnSelectedIndexChanged="committeeChange" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
EDIT: After being asked to provide more of the code, here is all of the C#.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
selection_form.Visible = false;
counties_div.Visible = false;
submit_button.ServerClick += new EventHandler(this.submitPressed);
}
public void displayAlert(String message)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + message + "');", true);
}
public void submitPressed(Object sender, EventArgs e)
{
if (username_field.Value == "")
{
this.displayAlert("Enter your username");
}
else if (password_field.Value == "")
{
this.displayAlert("Enter your password");
}
else
{
// Validate credentials
String username = username_field.Value;
String password = password_field.Value;
WebRequest request = WebRequest.Create("https://membershipwebapp.azurewebsites.net/signin");
request.Method = "GET";
request.ContentType = "application/json";
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
var objArray = js.Deserialize<dynamic>(objText);
// Check if JSON array is empty
if (objArray.Length == 0)
{
// Display sign in error
this.displayAlert("Username or password was incorrect.Try again.");
}
else
{
Dictionary<String, dynamic> userDictionary = objArray[0];
home_title.InnerHtml = "Welcome, " + userDictionary["FirstName"];
// Display black book data
sign_in_form.Visible = false;
this.getCounties();
selection_form.Visible = true;
counties_div.Visible = true;
committee_list_title.Visible = false;
committee_list.Visible = false;
}
}
else
{
// Display error message
this.displayAlert("An error occurred");
}
response.Close();
}
}
public void countyChange(Object sender, EventArgs e)
{
if (county_list.Items[county_list.SelectedIndex].Value != "")
{
this.getCommittees();
committee_list_title.Visible = true;
committee_list.Visible = true;
}
}
public void getCounties()
{
WebRequest request = WebRequest.Create("https://membershipwebapp.azurewebsites.net/counties");
request.Method = "GET";
request.ContentType = "application/json";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
var objArray = js.Deserialize<dynamic>(objText);
// Check if JSON array is empty
if (objArray.Length == 0)
{
// Display error
this.displayAlert("Error getting counties");
}
else
{
county_list.Items.Add("");
for (int i = 0; i < objArray.Length; i++)
{
// Get dictionary and add county name to list
Dictionary<String, dynamic> countyDictionary = objArray[i];
String countyName = countyDictionary["county"];
county_list.Items.Add(countyName);
}
}
}
else
{
// Display error message
this.displayAlert("Error getting counties");
}
response.Close();
}
public void getCommittees()
{
String selectedCounty = county_list.Items[county_list.SelectedIndex].Value;
String url = "https://membershipwebapp.azurewebsites.net/committee/" + selectedCounty;
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
var objArray = js.Deserialize<dynamic>(objText);
// Check if JSON array is empty
this.displayAlert("committee array length: " + objArray.Length);
if (objArray.Length == 0)
{
// Display error
this.displayAlert("Error getting committees");
}
else
{
committee_list.Items.Add("");
for (int i = 0; i < objArray.Length; i++)
{
// Get dictionary and add county name to list
Dictionary<String, dynamic> committeeDictionary = objArray[i];
String committeeName = committeeDictionary["committee_name"];
committee_list.Items.Add(committeeName);
// committeeSelect.Items.Add(committeeName);
}
}
}
else
{
// Display error message
this.displayAlert("Error getting committees");
}
response.Close();
}
public void committeeChange(object sender, EventArgs e)
{
if (committee_list.Items[committee_list.SelectedIndex].Value != "")
{
// Display committee member info
}
}
}
Before selecting a county
After selecting a county

How to create multipe column on ajax auto complete?

I create a table for searching items on ajax auto complete, I want to design like that(Table-1):
There is my web service code:
[WebMethod]
public object[] GetResult(string prefixText, int count)
{
List<object> result;
result = new List<object>();
try
{
Some Database query...
while (rd.Read())
{
result.Add(new
{
ProductName = rd[0],
Pic= rd[1],
RecID = rd[2],
Properties= rd[3]
});
}
rd.Close();
con.Close();
}
catch (Exception ex)
{
}
return result.ToArray();
}
I add a List object for all data and its java script side:
<script type="text/javascript">
function onPopulated() {
var list = $find("ace").get_completionList();
var count = list.childNodes.length;
for (i = 0; i < count; i++) {
var item = list.childNodes[i]._value;
var name = item.ProductName ;
var kategory = item.Properties;
var RecID = item.RecID;
var Pic= item.Pic;
var url = "http://abc.com.tr/img/p_" + RecID + "_" + Pic+ "_01.jpg"
list.childNodes[i].innerHTML = '<span id="name"><table><tr style="width:260px;height:55px;" ><td><img width="50" height="50" style="position:relative;" src="' + url + '"/></td><td style="font-size:11px;font-weight:bold;min-height:20px;">'+ name + '</td></tr></table></span>';
//'<span id="name"><table style="width:260px;"><tr><td><img width="50" height="50" src="' + url + '"/></td><td><b style="font-size:12px;">' + name + '</b><br>' + kategory + '</td></tr></table></span>'
}
}
function onSelected() {
var i = $find("ace")._selectIndex;
var item = list.get_completionList().childNodes[i]._value;
$get("txtSearch").value = item.name;
}
</script>
i add a table it view like that(Table-2):
and finally its my ajax toolkit tag:
<asp:TextBox runat="server" ID="txtSearch" Width="261" />
<cc1:AutoCompleteExtender ID="txtSearch_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServicePath="WebService.asmx"
FirstRowSelected="true"
EnableCaching="false"
ServiceMethod="GetResult"
MinimumPrefixLength="1"
CompletionListCssClass="completionList"
CompletionListHighlightedItemCssClass="itemHighlighted"
CompletionListItemCssClass="listItem"
OnClientItemSelected="onSelected" OnClientPopulated="onPopulated"
BehaviorID="ace" TargetControlID="txtSearch">
</cc1:AutoCompleteExtender>
How to create table like table-1? Please help me Thanks for your answers
I think, the following link may help you : http://vincexu.blogspot.com/2009/01/custom-autocomplete-6-multicolumn.html
For the record pasting code from the above mentioned article.
ASPX
<head runat="server">
<title></title>
<link href="../Default.css" rel="stylesheet" type="text/css" />
<style>
.cloumnspan
{
width:35px;
padding:0px;
border-color:Black;
border-style:solid;
border-width:1px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1" />
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<ajaxToolkit:AutoCompleteExtender
runat="server" OnClientPopulated="dd" OnClientItemSelected="itemSelected"
BehaviorID="AutoCompleteEx"
ID="autoComplete1"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList5"
MinimumPrefixLength="2"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="8"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :">
</ajaxToolkit:AutoCompleteExtender>
</form>
<script type="text/javascript">
function itemSelected(ev)
{
var index=$find("AutoCompleteEx")._selectIndex;
var value=$find("AutoCompleteEx").get_completionList().childNodes[index]._value;
$find("AutoCompleteEx").get_element().value = value;
}
function dd()
{
var comletionList=$find("AutoCompleteEx").get_completionList();
for(i=0;i<comletionList.childNodes.length;i++) {
var itemobj=new Object();
var _data = comletionList.childNodes[i]._value;
itemobj.name= _data.substring(_data.lastIndexOf('|') + 1); // parse name as item value
comletionList.childNodes[i]._value = itemobj.name;
_data = _data.substring(0, _data.lastIndexOf('|'));
itemobj.age = _data.substring(_data.lastIndexOf('|') + 1);
_data = _data.substring(0, _data.lastIndexOf('|'));
itemobj.id = _data.substring(_data.lastIndexOf('|') + 1);
comletionList.childNodes[i].innerHTML = "<div class='cloumnspan' style='width:10%;float:left'>" + itemobj.id + "</div>"
+ "<div class='cloumnspan' style='width:70%;float:left'>" + itemobj.name + "</div>"
+ "<div class='cloumnspan' style='width:18%;'>" + itemobj.age + "</div>";
}
}
</script>
</body>
Web Method:
[WebMethod]
public string[] GetCompletionList5(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
if (prefixText.Equals("xyz"))
{
return new string[0];
}
Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char)random.Next(65, 90);
char c2 = (char)random.Next(97, 122);
char c3 = (char)random.Next(97, 122);
int id = i;
int age = random.Next(18, 70);
items.Add(id.ToString() + "|" + age.ToString() + "|" + prefixText + c1 + c2 + c3);
}
return items.ToArray();
}

Ajax call start loading like a freak

I have a site for testing Ajax... and it works:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="AJAX.aspx.cs" Inherits="HB___test.AJAX" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Ajax() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("No AJAX!?");
return false;
}
}
}
xmlHttp.onreadystatechange = function () {
document.getElementById('chat').innerHTML = xmlHttp.responseText;
setTimeout('Ajax()', 10000);
}
xmlHttp.open("GET", "ajax-Content.aspx", true);
xmlHttp.send(null);
}
window.onload = function () {
setTimeout('Ajax()', 10000);
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
Kummefryser...!
<div id="chat" class="fisk" style="width: 500px; height: 500px">
</div>
</asp:Content>
And here is the site it's laoding:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ajax-Content.aspx.cs" Inherits="HB___test.ajax_Content" %>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lbChat" runat="server" Rows="10" Width="400px"></asp:ListBox>
</div>
</form>
</body>
And the codebehind for the above site:
public partial class ajax_Content : System.Web.UI.Page
{
grjenie31Entities gr;
protected void Page_Load(object sender, EventArgs e)
{
gr = new grjenie31Entities();
var query = from es in gr.chats
where es.id > ((from esh in gr.chats select esh.id).Max() - 15)
orderby es.timestamps descending
select es;
List<chat> list = new List<chat>();
foreach (chat chat in query)
{
list.Add(chat);
}
for (int i = 0; i < list.Count; i++)
{
lbChat.Items.Add("[" + list[i].timestamps + "] " + list[i].personID.ToString() + ": " + list[i].besked);
}
this.lbChat.SelectedIndex = this.lbChat.Items.Count - 1;
}
}
But when I load the site ajax-Content.aspx it start reloading freakingly fast... so in 30 seconds I can't read the text it load in the ajax.Content.aspx site.
Any ideas??
xmlHttp.onreadystatechange fires not only on success, you should only start the new timeout on readystate 4
furtherMore you should define a variable for the timeout to be able to clear an existing timeout before running a new.

how to access values returned by google feed api in page load?

am currently using google feed api to get feed links dynamically. am trying to use the results returned by the api to create rss feed for my website..Now the problem is api function call takes place only after the page load so i cant access the url values returned by the api in page load function..
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAAxII5vpTAk5gatTPIMAFoCxStIDvCAqMV0_KActMytIL1qEezxxQeBqRzIurcFfnrUgG2YMlC07VgbQ"></script>
<script type="text/javascript">
google.load("feeds", "1", { "callback": OnLoad });
function OnLoad() {
// Query for president feeds on cnn.com
var query = 'atlanta bridal shows';
google.feeds.findFeeds(query, findDone);
}
function findDone(result) {
// Make sure we didn't get an error.
if (!result.error) {
// Get content div
var content = document.getElementById('content');
var html = '';
var submenu = new Array()
// Loop through the results and print out the title of the feed and link to
// the url.
for (var i = 0; i < result.entries.length; i++) {
var entry = result.entries[i];
html += '<p>' + entry.title + '</p>';
submenu[i] = entry.url;
}
content.innerHTML = html;
document.getElementById('<%= Hidden1.ClientID %>').value = submenu;
}
}
google.setOnLoadCallback(OnLoad);
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:HiddenField ID="Hidden1" runat="server" ondatabinding="Hidden1_DataBinding"
onunload="Hidden1_Unload" onvaluechanged="Hidden1_ValueChanged" />
<div id="content"></div>
</asp:Content>
pageload event:
protected void Page_Load(object sender, EventArgs e)
{
WebClient client = new WebClient();
string path = Request.Url.GetLeftPart(UriPartial.Authority) +
VirtualPathUtility.ToAbsolute("~/user/feed.htm");
Stream stream = client.OpenRead(path);
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
}
What should i do to access the values returned by the api in page load??
First of all you have to create feed.htm and put above code in it.
feed.htm (which is located at root of web-app)
<script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAAxII5vpTAk5gatTPIMAFoCxStIDvCAqMV0_KActMytIL1qEezxxQeBqRzIurcFfnrUgG2YMlC07VgbQ"></script>
<script type="text/javascript">
google.load("feeds", "1", { "callback": OnLoad });
function OnLoad() {
// Query for president feeds on cnn.com
var query = 'atlanta bridal shows';
google.feeds.findFeeds(query, findDone);
}
function findDone(result) {
// Make sure we didn't get an error.
if (!result.error) {
// Get content div
var content = document.getElementById('content');
var html = '';
var submenu = new Array()
// Loop through the results and print out the title of the feed and link to
// the url.
for (var i = 0; i < result.entries.length; i++) {
var entry = result.entries[i];
html += '<p>' + entry.title + '</p>';
submenu[i] = entry.url;
}
content.innerHTML = html;
document.getElementById('<%= Hidden1.ClientID %>').value = submenu;
}
}
google.setOnLoadCallback(OnLoad);
</script>
<div id="content"></div>
Then after in page_load event of .aspx page use System.Net.WebClient class methods to request the feed.htm.
TestFeed.aspx (which is located at root of web-app)
Markup:
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
WebClient client = new WebClient();
string path = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/feed.htm");
Stream stream = client.OpenRead(path);
StreamReader sr = new StreamReader(stream);
//To view the result
Label1.Text = sr.ReadToEnd();
}

How can I retrieve query string from my webpage .ASPX to my HTML file script?

Here is my Code in my page 'Welcome.aspx.cs':
protected void Page_PreRender(object sender, EventArgs e)
{
string menus = string.Empty;
if (this.hfAccessLvl.Value == string.Empty)
{
Response.Redirect("login.aspx");
}
myMenu.Text = AlMenu("js/MyMenu.html?accesLevel=" + this.hfAccessLvl.Value + "|" + virtualDrive, "no", "400px", "100");
}
In my MyMenu.html code:
<html>
<body runat="server">
<form id="form1" runat="server">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html;CHARSET=iso-8859-1" />
<title>Test Only</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script language="JavaScript" src="crossbrowser.js" type="text/javascript"></script>
<script language="JavaScript" src="outlook.js" type="text/javascript"></script>
<script type="text/javascript">
var o = new createOutlookBar('Bar',0,0,screenSize.width,screenSize.height,'#606060','white')
var p
var accessLevell = GetQueryString('accesLevel').split('|')[0]; // Get Access level of user
var virtualDrive = GetQueryString('accesLevel').split('|')[1]; // Get Virtual drive that was set if any...
//create first panel
p = new createPanel('al','Nestle Web Sites');
p.addButton('home.gif','Home','parent.location="' + virtualDrive + '/Welcome.aspx"');
p.addButton('home.gif','Log-Out','parent.location="' + virtualDrive + '/Login.aspx"');
o.addPanel(p);
o.draw();
</script>
</head>
</form>
</body>
</html>
Now I want to get the query string value that I'd pass from Welcome.aspx.cs in my MyMenu.html script file:
var accessLevell = GetQueryString('accesLevel').split('|')[0];
var virtualDrive = GetQueryString('accesLevel').split('|')[1];
Try this:
function GetQueryString( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
(code taken from http://www.netlobo.com/url_query_string_javascript.html )

Categories

Resources