How to create multipe column on ajax auto complete? - c#

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

Related

How to bind data to grid column using array

aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/HomeMaster.master" AutoEventWireup="true" CodeFile="V_MaterCode.aspx.cs" Inherits="V_MaterCode" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "V_MaterCode.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grd_mastercodes").append("<tr><td>" + data.d[i].Vendor + "</td><td>" + data.d[i].SearchTerm + "</td><td>" + data.d[i].Vendor_Name + "</td><td>" + data.d[i].Street + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td><td>" + data.d[i].PO_Box + "</td><td>" + data.d[i].Currency + "</td><td>" + data.d[i].Sales_Person + "</td><td>" + data.d[i].Telephone_Number + "</td><td>" + data.d[i].Ext_01 + "</td><td>" + data.d[i].Ext_02 + "</td><td>" + data.d[i].Minimum_Value + "</td><td>" + data.d[i].Post_Code + "</td><td>" + data.d[i].Group + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" LoadScriptsBeforeUI="false"
EnablePartialRendering="false">
</asp:ScriptManager>
<div class="contentarea">
<br />
<asp:Label ID="lblsub" Style="overflow-x: auto; margin-left: 20px;" runat="server" Text="Station master data entry" />
</div>
<div style="margin: 0 auto; overflow: auto; padding: 10px 20px;">
<asp:GridView ID="grd_mastercodes" runat="server" HeaderStyle-BackColor="#f79646" HeaderStyle-ForeColor="White"
HeaderStyle-Font-Bold="false" Font-Names="Calibri"
Font-Size="Medium" RowStyle-BackColor="White" HeaderStyle-BorderColor="Black"
AutoGenerateColumns="False" RowStyle-BorderColor="Black" OnRowCreated="grd_mastercodes_RowCreated">
</asp:GridView>
</div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using AjaxControlToolkit;
public partial class V_MaterCode : System.Web.UI.Page
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
bool rowset = false;
GridView dgv = new GridView();
// For First gridview
String[] gridColumnNames_mastercodes = { "Vendor Code", "Search Term", "Vendor Name", "Street", "City", "Country", "Post Box", "Currency", "Sales Person", "Telephone Number", "Ext_01", "Ext_02", "Minimum Value", "Post Code", "Group" };
String[] gridColumnwidth_mastercodes = { "50px", "200px", "200px", "150px", "100px", "100px", "100px", "100px", "150px", "150px", "150px", "150px", "100px", "100px", "100px" };
int[] gridColumnWidth_mastercodes = { 3, 15, 15, 13, 10, 10, 10, 10, 13, 13, 13, 13, 10, 10, 10 };
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
//For First gridview
DataTable dt = new DataTable();
for (int c = 0; c < gridColumnNames_mastercodes.Length; c++)
{
DataColumn dcol = new DataColumn(c.ToString(), typeof(System.Int32));
dcol.ColumnName = gridColumnNames_mastercodes[c];
dt.Columns.Add(dcol);
TemplateField tf = new TemplateField();
tf.HeaderStyle.Font.Bold = false;
tf.HeaderText = gridColumnNames_mastercodes[c];
tf.HeaderStyle.Width = new Unit(gridColumnwidth_mastercodes[c]);
grd_mastercodes.Columns.Add(tf);
}
for (int i = 0; i < 15; i++)
{
dt.Rows.Add(dt.NewRow());
}
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
BindColumnToGridview();
}
private void BindColumnToGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("Vendor");
dt.Columns.Add("Search Term");
dt.Columns.Add("Vendor Name");
dt.Columns.Add("Street");
dt.Columns.Add("City");
dt.Columns.Add("Country");
dt.Columns.Add("Post Box");
dt.Columns.Add("Currency");
dt.Columns.Add("Sales Person");
dt.Columns.Add("Telephone Number");
dt.Columns.Add("Ext_01");
dt.Columns.Add("Ext_02");
dt.Columns.Add("Minimum Value");
dt.Columns.Add("Post Code");
dt.Columns.Add("Group");
dt.Rows.Add();
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
//grd_mastercodes.Rows[0].Visible = false;
}
[WebMethod]
public static UserDetails[] BindDatatable()
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
DataTable dt = new DataTable();
List<UserDetails> details = new List<UserDetails>();
using (SqlConnection con = new SqlConnection(connectionstring))
{
using (SqlCommand cmd = new SqlCommand("Select * From ArR_VendorMaster", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.Vendor = dtrow["Vendor"].ToString();
user.SearchTerm = dtrow["SearchTerm"].ToString();
user.Vendor_Name = dtrow["Vendor_Name"].ToString();
user.Street = dtrow["Street"].ToString();
user.City = dtrow["City"].ToString();
user.Country = dtrow["Country"].ToString();
user.PO_Box = dtrow["PO_Box"].ToString();
user.Currency = dtrow["Currency"].ToString();
user.Sales_Person = dtrow["Sales_Person"].ToString();
user.Telephone_Number = dtrow["Telephone_Number"].ToString();
user.Ext_01 = dtrow["Ext_01"].ToString();
user.Ext_02 = dtrow["Ext_02"].ToString();
user.Minimum_Value = dtrow["Minimum_Value"].ToString();
user.Post_Code = dtrow["Post_Code"].ToString();
user.Group = dtrow["Group"].ToString();
details.Add(user);
}
}
}
return details.ToArray();
}
public class UserDetails
{
public string Vendor { get; set; }
public string SearchTerm { get; set; }
public string Vendor_Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PO_Box { get; set; }
public string Currency { get; set; }
public string Sales_Person { get; set; }
public string Telephone_Number { get; set; }
public string Ext_01 { get; set; }
public string Ext_02 { get; set; }
public string Minimum_Value { get; set; }
public string Post_Code { get; set; }
public string Group { get; set; }
}
//For First Gridview
protected void grd_mastercodes_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int rc = 0; rc < grd_mastercodes.Columns.Count; rc++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "Excel_mastercodes" + e.Row.RowIndex + "_" + rc;
txtBox.MaxLength = gridColumnWidth_mastercodes[rc];
txtBox.Width = new Unit(gridColumnwidth_mastercodes[rc]);
txtBox.BorderStyle = BorderStyle.None;
e.Row.Cells[rc].Controls.Add(txtBox);
e.Row.Cells[rc].Attributes.Add("onKeyDown", "enter(this);");
if (rc == 3)
txtBox.Style["text-align"] = "left";
else
txtBox.Style["text-align"] = "center";
}
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
}
}
I need to bind data but it displaying column name only . It's not binding any data . weather i am doing in a correct . If any body knows how to get data please suggest me. I am using array and i am not sure how to bind data in array . I need your help

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

asp.net add html elements from static method

I trying to add HTML or image button which can call code behind method, from a static method(Web method), I am calling web method through AJAX. My code is:
AJAX Method
function dispData()
{
var text_data = document.getElementById("TextBox1").value;
var text_count = text_data.length;
if (text_count >= 4)
{
alert("Text box val = " + text_data + " :Count = " + text_count);
$.ajax({
type: "POST",
url: "WebForm2.aspx/ajaxData",
data: JSON.stringify({ data: text_data }),
contentType: 'application/json; charset=utf-8',
dataType: "JSON",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
//alert("We returned: " + result.d);
$('#disp_ajax_data').html(result.d);<-- displaying result in div
}
})
return false;//end of ajax
}//end of if text_count.
}//end of dispData.
[WebMethod(TransactionOption = TransactionOption.Supported)]
public static string ajaxData(string data)
{
for (int loopCount = 0; loopCount < myCount; loopCount++)
{
string ele = oCompInfoSet[loopCount].Name + "<a href='codeBehindMethod()'>Add</a>" + "<br>";
returnVal += ele;
}//end for loop.
}
I am displaying the names properly but not able to get the buttons. Can anyone please help
EDIT:
From deostroll's help, my changed code, Oh... silly me.... I missed 'Static' keyword. I am trying to pass value now
for (int loopCount = 0; loopCount < oCompInfoSet.ComponentCount; loopCount++)
{
//Debug.WriteLine("In for loop");
string ele_name = oCompInfoSet[loopCount].Component.Name;
string ele = ele_name + "<a href='#' OnClick='add_ele("+ele_name+")'>Add</a> <br>";
returnVal += ele;
}//end for loop.
[WebMethod(TransactionOption = TransactionOption.Supported)]
public static void addToStream()
{
Debug.WriteLine("Add to stream here");
}//end of addToStream
JS METHOD:
function add_ele(name)
{
alert("add ele called, "+name);
//PageMethods.addToStream();
}//end of add_ele.
I am not getting alert also now, getting "Unidentified Error"....
Try looking at this: http://visualstudiomagazine.com/articles/2007/08/28/creating-and-consuming-aspnet-ajax-page-methods.aspx
The article above utilizes a concept called Page Methods. You have to enable it on the ScriptManager. Here is a simple example that is kind of in line with what you are doing:
Aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.PageMethods.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Page Methods</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager>
<div>
<input type="button" onclick="GenerateLinks(5)" value="Add Links" />
<div id="links"></div>
<ul id="result">
</ul>
</div>
</form>
<script>
/*
*
* to generate guid
*
*/
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function GetTime() {
var g = guid();
log('sent request for ' + g);
PageMethods.GetTime(g, GetTimeSuccess);
}
function GetTimeSuccess(result) {
log('result:' + result);
}
function GenerateLinks(n) {
log('Generating links');
PageMethods.GenerateLinks(n, function (result) {
document.getElementById('links').innerHTML = result;
log('added links');
});
}
function log(msg) {
var dt = new Date();
var format = function(number){
return number < 10 ? '0' + number : number
};
var h = format(dt.getHours());
var m = format(dt.getMinutes());
var s = format(dt.getMinutes());
var ul = document.getElementById('result');
var li = document.createElement('li');
li.innerHTML = h + ':' + m + ':' + s + ' - ' + msg;
ul.appendChild(li);
}
</script>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Web.Services;
namespace WebApp.PageMethods
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GenerateLinks(int number)
{
List<string> a = new List<string>();
for (int i = 0; i < number; i++)
{
a.Add("Get Time " + (i + 1) + "");
}
return string.Join("<br/>", a);
}
[WebMethod]
public static string GetTime(string guid)
{
return guid + " / " + DateTime.Now.ToLongTimeString();
}
}
}

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 call a javascript function to bind a dynamically added div

I have a calender control and on selecting a respective date, I need to display Today's Due and Over due as two section in an accordion. I tried adding div with style to give the look of accordion but that is giving UI issues.Currently,I am planning to add Accordion (Jquery).Since, the accordion is to be displayed while selecting a date from calender control. I am binding the accordion div in code behind and converting it to Json to be shown, while selecting the respective date.The code to add the div is as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CalenderBinderAccordian()
{
try
{
//Code to fetch ProductGroup is not shown
foreach (var p in productGroup)
{
string todoString = "";
int uniqueID = Guid.NewGuid().GetHashCode();
todoString = "<div id='accordion' class='ui-accordion ui-widget ui-helper-reset' role='tablist'><h3><b>Due Today</b></h3>";
todoString += "<div>";
foreach (var t in p.todo)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
todoString += "<p style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='PaymentDetails.aspx' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></p>";
todoCount++;
}
todoString += "</div>";
var overDue = temps.Select(x => new { x.DueDate }).Distinct().ToList();
int overDueCount = 0;
uniqueID = Guid.NewGuid().GetHashCode();
todoString += "<h3><b>Over Due</b></h3>";
int todoCount1 = 1;
todoString += "<div>";
for (int i = 0; i < overDue.Count(); i++)
{
if ((Convert.ToDateTime(overDue[i].DueDate) - Convert.ToDateTime(p.dates)).Days < 0)
{
overDueCount++;
var overDueList = temps.FindAll(x => x.DueDate.Equals(overDue[i].DueDate)).ToList();
foreach (var t in overDueList)
{
var tempAmt = String.Empty;
if ((t.Amount == null) || t.Amount == String.Empty)
tempAmt = "0";
else
tempAmt = Convert.ToDecimal(t.Amount.ToString()).ToString();
todoString += "<p style='padding:5px 0px; border-bottom:dashed 1px #dddddd;'><b>" + todoCount1.ToString() + "</b>. " + t.ProductName + "<span style='text-align:right; padding-right:5px;'> $" + tempAmt + "</span><a href='PaymentDetails.aspx' target='_blank' style='text-decoration:none;'><b>Pay Now</b></a></p>";
todoCount++;
todoCount1++;
}
}
}
todoString += "</div>";
todoString = todoString + "</div>\",\"count\":\"" + todoCount + "\"},";
jsonString = jsonString + String.Format("{{\"{0}\" : \"{1}\",\"{2}\" : \"{3}", "dates", p.dates, "todo", todoString);
if (overDueCount.Equals(0))
{
jsonString = jsonString.Replace("<h3><b>Over Due</b></h3><div></div>", "");
}
}
jsonString = jsonString.TrimEnd(',');
jsonString = '[' + jsonString + ']';
string data= jsonString;
return data;
}
catch (Exception ex)
{
throw;
}
}
The code in the ascx page is as follows:
/
/Scripts for Calender control
<script type="text/javascript" src="../../Scripts/jquery-1.8.3.js"></script>
<link rel="stylesheet" href="../../Content/jquery.calendarPicker.css" type="text/css" media="screen"/>
<script type="text/javascript" src="../../Scripts/jquery.calendarPicker.js"></script>
<link rel="stylesheet" href="../../Content/style.css" type="text/css" media="screen"/>
//Scripts for accordion
<link rel="stylesheet" href="../../Content/jquery-ui.css" />
<script type="text/javascript" src="../../Scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#accordion").accordion();
});
</script>
<div class="calendercontent">
<div id="dsel1" style="width:200px;">
<span id="span1"></span>
</div>
<img class="ref" src="../../Images/refresh_circle.gif" alt="refresh" title="refresh"/>
<div id="todo"></div>
</div>
It is noticed that when I add the div data in the ascx page the accordion works fine and using fireBug the accordion class are shown.But since the accordion data is added in the code behind and displayed using java script.The below displayed function is not working.
Kindly help, I am a beginner in Jquery.
<script type="text/javascript">
$(function () {
$("#accordion").accordion();
});
</script>
Try with this:
$(document).find("#accordion").accordion();
this is because the accordion function is called when the DOM is ready $(function () {... and by thn the dynamically added div is not there in the DOM.. so
call the accordion function after the dynamically generated div is displayed..
//code to display your dynamic div..
$("#addedDivID").accordion(); //call the accordion function (again) after that..

Categories

Resources