DropDownList Not Visible After Selecting Item - c#

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

Related

SheerResponse ShowModalDialog doesn't return a result

I'm working with sitecore 8 Update 2.
I'm extending the TreelistEx field.
The user is presented with a modal dialog ( created by Sheerresponse using QuickContact.html ).
Here the user can fill in 4 fields. When the user clicks "OK" the value of these fields are saved into an object. I would like to return this object/values. I have however found no way to achieve this.
( The ClientPipelineArgs never returns with any result )
namespace be.absi.kbs.extensions
{
class AbsiTreeListEx : TreelistEx, IMessageHandler
{
void IMessageHandler.HandleMessage(Message message)
{
if (message == null)
{ return; }
if (message["id"] == null)
{ return; }
if (!message["id"].Equals(ID))
{ return; }
var fieldInfo = _fieldInformation[message["id"]];
switch (message.Name)
{
case "treelist:edit":
var nvcEdit = new NameValueCollection { { "source", fieldInfo.Source } };
Sitecore.Context.ClientPage.Start(this, "Edit", nvcEdit);
break;
case "absitreelistex:absiquickadd":
var nvcQuickAdd = new NameValueCollection { { "clientFieldId", message["id"] } };
Sitecore.Context.ClientPage.Start(this, "QuickAddItem", nvcQuickAdd);
break;
}
}
protected void QuickAddItem(ClientPipelineArgs args)
{
if (args.IsPostBack)
{
// GET information from the QuickContact.html
}
else
{
var options = new ModalDialogOptions("/QuickContact.html")
{
Closable = true,
Response = true
};
SheerResponse.ShowModalDialog(options);
args.WaitForPostBack();
}
}
}
}
QuickContact.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base target="_self">
<title></title>
<script type="text/javascript">
function sendResponse()
{
var o = new Object();
o.forename = document.getElementById("FirstNameId").value;
o.surname = document.getElementById("LastNameId").value;
o.phone = document.getElementById("PhoneId").value;
o.mail = document.getElementById("MailId").value;
window.returnValue = o;
return o;
}
function OK()
{
var returnVal = sendResponse();
var jQueryResult = window.parent.$('.ui-dialog-content:visible');
self.returnValue = returnVal;
document.returnValue = returnVal;
window.returnValue = returnVal;
jQueryResult.dialog('close');
}
</script>
</head>
<body>
<label style="min-width: 80px;">First Name: </label><input type="text" id="FirstNameId" /><br />
<label style="min-width: 80px;">Last Name: </label><input type="text" id="LastNameId" /><br />
<label style="min-width: 80px;">Phone: </label><input type="text" id="PhoneId" /><br />
<label style="min-width: 80px;">Mail: </label><input type="text" id="MailId" /><br />
<br />
<input type="button" value="OK" onclick="OK()" />
</body>
</html>
Try setting result value with window.top.returnValue = returnVal; in JavaScript and reading it with args.Result iny our C# code. This worked for me.
I didn't realy find a legit solution for this issue.
I did solve it by writing my result to a coockie and reading it server-side ( deleting it afterwards )

In Facebook with C# /me/accounts with manage_pages permission does not show any pages

I am trying to fetch pages data in Facebook using c# MVC. Even though I give manage_pages permission (Scope) it does not show any pages when I run my code. Here is where pagelist is showing 0
string Accounts = "/me/accounts";
JSONObject pageData = api.Get(Accounts);
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
ViewBag.pageList = pageList;
Below is the Code that I tried
public ActionResult returnfromfb()
{
string app_id = "AppID";
string app_secret = "AppSecret";
string scope = "manage_pages,publish_stream,status_update,user_about_me,user_hometown,user_location,email,offline_access";
string code = Request.QueryString["code"];
if (code == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
string AccessToken = "";
try
{
if (code != null)
{
string str = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(str);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] Param = Request.BinaryRead(System.Web.HttpContext.Current.Request.ContentLength);
string strRequest = System.Text.Encoding.ASCII.GetString(Param);
req.ContentLength = strRequest.Length;
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
if (strResponse.Contains("&expires"))
strResponse = strResponse.Substring(0, strResponse.IndexOf("&expires"));
AccessToken = strResponse.Replace("access_token=", "");
streamIn.Close();
}
Facebook.FacebookAPI api = new Facebook.FacebookAPI(AccessToken);
string requestEmail = "/me";
JSONObject fbemail = api.Get(requestEmail);
try
{
ViewBag.Email = fbemail.Dictionary["email"].String;
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
string Accounts = "/me/accounts";
JSONObject pageData = api.Get(Accounts);
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
ViewBag.pageList = pageList;
foreach (var page in pageList)
{
try
{
var id = page.Dictionary["id"].String;
string request = id;
JSONObject fbobject = api.Get(request);
try
{
ViewBag.BusinessName = fbobject.Dictionary["name"].String;
ViewBag.Address = fbobject.Dictionary["location"].ToDisplayableString();
ViewBag.PhoneNumber = fbobject.Dictionary["phone"].String;
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
}
catch (Exception ex)
{
//errorLog.setError(ex, "LoginController.SaveFacebookData");
}
}
I have Finally managed to get the desired result using #Remodal.js
<head>
<link rel="stylesheet" href="#Url.Content("~/Content/jquery.remodal.css")">
</head>
<body>
<script type="text/javascript" src="#Url.Content("~/Scripts/Home/jquery.remodal.js")"></script>
<div class="remodal" id="page-selector-remodal" data-remodal-id="pageselector">
<p>Please select a facebook page Share </p>
<div id="page-name-container">
<select id="page-name" class="form-control">
</select>
</div>
<a class="remodal-confirm" id="facebookPageSelectSubmit" href="#">OK</a>
<a class="remodal-cancel" id="remodal-cancel" href="#">CANCEL</a>
</div>
<div data-remodal-id="modal-status">
<p id="modal-status-content">
The Account you have selected does not have Email.
</p>
<br>
<a class="remodal-confirm" href="#">OK</a>
</div>
<script type="text/javascript>
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function () {
FB.init({
appId: 'YOUR APP ID',
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.2' // use version 2.1
});
};
var pageSelector = $('[data-remodal-id=pageselector]').remodal();
var modalstatus = $('[data-remodal-id=modal-status]').remodal();
function statusChangeCallback(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
//testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
}
else {
$("#modal-status-content").empty().html(response.status);
modalstatus.open();
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
function FacebookHandler() {
FB.login(function (result) {
if (result != null && result.authResponse != null && result.authResponse != undefined) {
facebookPageData = result;
FB.api('/me/accounts', function (accountsResult) {
if (accountsResult != null && accountsResult.data.length != 0) {
//open the remodal here
pageSelector.open();
facebookAccountsData = accountsResult;
var data = accountsResult['data'];
if (data != null) {
for (var i = 0; i < data.length; i++) {
$("#page-name").append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
}
}
unblockUI('body');
$("#flip-container, #feature-container, #branding-container, #intro-arrow-container, #share-container, #copyright-text-container").hide();
$("body").css("padding-right", "0");
}
else {
$("#modal-status-content").empty().html("The Account you have selected does not have any facebook page,<br />Post to Wall.");
modalstatus.open();
pageSelector.open();
unblockUI('body');
}
});
}
else {
$("#modal-status-content").empty().html("Unable to retrieve your details from facebook, try again after sometime.");
modalstatus.open();
unblockUI('body');
}
}, { scope: 'manage_pages, publish_stream' });
}
$("#facebookPageSelectSubmit").on("click", function () {
var facebookpageId = $("#page-name option:selected").val();
if (facebookpageId != null) {
FB.api('/' + facebookpageId, function (identity) {
if (identity != null) {
FB.api('/' + facebookpageId, { fields: 'access_token' }, function (resp) {
if (resp.access_token != null) {
//Get the "resp"(Data) here
}
else {
}
});
}
else {
}
});
}
else {
}
});
</script>
//Finally call the "FacebookHandler()" function on click
</body>

Update MasterPage control from Content page

I have an UpdatePanel with a Label which I would like to update in my MasterPage. The event is taking place from my Content page and here are the codes.
Content ASP.net code:
<%# MasterType TypeName="OnBoarding.Pages.Site" %>
<asp:DropDownList ID="ddlTaskName" CssClass="chosen-select" DataSourceID="dsPopulateTaskName" AutoPostBack="true" DataValueField="Task Name" runat="server" Width="100%" Font-Size="11px" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlTaskName_onSelectIndexChanged">
<asp:ListItem Text="All" Value="%"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="dsPopulateTaskName" runat="server" ConnectionString="<%$ ConnectionStrings:gvConnString %>" SelectCommand="QUERY"></asp:SqlDataSource>
C# code-behind:
protected void ddlTaskName_onSelectIndexChanged(object sender, EventArgs e)
{
FilterMessages();
}
public void FilterMessages()
{
DataTable msgTable = HttpContext.Current.Session["MessageTable"] as DataTable;
string query = "";
Stack msgStack = new Stack();
if (ddlClient.SelectedIndex > 0)
{
query += "Client = '" + ddlClient.SelectedItem.Text + "' OR Client is NULL";
}
if (ddlSite.SelectedIndex > 0 && query == "")
{
query += "Site = '" + ddlSite.SelectedItem.Text + "' OR Site is NULL";
}
else if (ddlSite.SelectedIndex > 0)
{
query += " AND Site = '" + ddlSite.SelectedItem.Text + "' OR Site is NULL";
}
if (ddlProvider.SelectedIndex > 0 && query == "")
{
query += "Provider = '" + ddlProvider.SelectedItem.Text + "' OR Provider is NULL";
}
else if (ddlProvider.SelectedIndex > 0)
{
query += " AND Provider = '" + ddlProvider.SelectedItem.Text + "' OR Provider is NULL";
}
UpdatePanel upMsg = (UpdatePanel)Master.FindControl("upMessage");
if (query != "")
{
DataRow[] result = msgTable.Select(query);
System.Web.UI.WebControls.Label lblMsg = (System.Web.UI.WebControls.Label)Master.FindControl("lblMessage");
if (lblMsg != null)
{
lblMsg.Text = "";
}
//lblMessage.Text = "";
foreach (DataRow row in result)
{
if (row["Active"].ToString() == "True")
{
string[] myStrings = new string[] { row["Created"].ToString().Split(' ')[0], string.IsNullOrEmpty(row["Client"].ToString()) ? null : row["Client"].ToString(), string.IsNullOrEmpty(row["Site"].ToString()) ? null : row["Site"].ToString(), row["Message"].ToString() };
string strResult = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));
msgStack.Push(strResult);
}
}
foreach (string message in msgStack)
{
lblMsg.Text += message + "</br>";
//lblMessage.Text += message + "</br>";
}
}
else
{
PopulateMessageGV();
}
if (upMsg != null)
{
upMsg.Update();
}
//upMessage.Update();
}
protected void PopulateMessageGV()
{
UpdatePanel upMsg = (UpdatePanel)Master.FindControl("upMessage");
System.Web.UI.WebControls.Label lblMsg = (System.Web.UI.WebControls.Label)Master.FindControl("lblMessage");
if (lblMsg != null)
{
lblMsg.Text = "";
}
//lblMessage.Text = "";
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Created", typeof(string));
dt.Columns.Add("Message", typeof(string));
dt.Columns.Add("Client", typeof(string));
dt.Columns.Add("Site", typeof(string));
dt.Columns.Add("Provider", typeof(string));
dt.Columns.Add("Active", typeof(bool));
dt.Columns.Add("CreatedBy", typeof(string));
using (var context = new ClientContext(hostWeb))
{
Stack msgStack = new Stack();
var hostSite = context.Web;
context.Load(hostSite, s => s.Title);
context.ExecuteQuery();
ListCollection allLists = hostSite.Lists;
Microsoft.SharePoint.Client.List messageList = allLists.GetByTitle("AdminMessage");
context.Load(messageList);
context.ExecuteQuery();
try
{
var query = CamlQuery.CreateAllItemsQuery();
Microsoft.SharePoint.Client.ListItemCollection allItems = messageList.GetItems(query);
context.Load(allItems);
context.ExecuteQuery();
if (allItems.Count > 0)
{
foreach (Microsoft.SharePoint.Client.ListItem item in allItems)
{
DataRow dr = dt.NewRow();
dr["ID"] = item["ID"];
dr["Created"] = item["Created"];
dr["Message"] = item["Message"];
dr["Client"] = item["Client"];
dr["Site"] = item["Site"];
dr["Provider"] = item["Provider"];
dr["Active"] = item["Active"];
FieldUserValue test = (FieldUserValue)item["Author"];
dr["CreatedBy"] = test.LookupValue.ToString();
dt.Rows.Add(dr);
if (item["Active"].ToString() == "True")
{
string[] myStrings = new string[] { item["Created"].ToString().Split(' ')[0], string.IsNullOrEmpty(dr["Client"].ToString()) ? null : item["Client"].ToString(), string.IsNullOrEmpty(dr["Site"].ToString()) ? null : item["Site"].ToString(), item["Message"].ToString() };
string result = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));
msgStack.Push(result);
}
}
}
HttpContext.Current.Session["MessageTable"] = dt;
foreach (string message in msgStack)
{
lblMsg.Text += message + "</br>";
//lblMessage.Text += message + "</br>";
}
if (upMsg != null)
{
upMsg.Update();
}
//upMessage.Update();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
MasterPage ASP.net code:
<asp:UpdatePanel runat="server" ID="upMessage" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" Font-Size="x-small" runat="server" Text="" ClientIDMode="Static"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
When I change the DropDown option the UpdatePanel in the masterpage doesn't update although putting a breakpoint there, shows that it is being hit.
How do I resolve the issue?
Basically, you want to expose Public Property from MasterPage. Then access it from ContentPage.
Master Page
<%# Master Language="C#" AutoEventWireup="true"
CodeBehind="Site.Master.cs" Inherits="DemoWebForm.Site" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="MessageLabel" />
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
</html>
public partial class Site : System.Web.UI.MasterPage
{
public string MessageLabelText
{
get { return MessageLabel.Text; }
set { MessageLabel.Text = value; }
}
}
Content Page
<%# Page Title="Home Page" Language="C#"
MasterPageFile="~/Site.Master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DemoWebForm._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:DropDownList ID="TaskNameDropDownList"
runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="TaskNameDropDownList_SelectedIndexChanged">
<asp:ListItem Text="One" Value="1" />
<asp:ListItem Text="Two" Value="2" />
</asp:DropDownList>
</asp:Content>
public partial class _Default : Page
{
protected void TaskNameDropDownList_SelectedIndexChanged(
object sender, EventArgs e)
{
var master = Master as Site;
if (master != null)
{
master.MessageLabelText = TaskNameDropDownList.SelectedValue;
}
}
}

Javascript not working with Ext.Net

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);
}

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();
}

Categories

Resources