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..
Related
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();
}
}
}
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);
}
I want to append a query called ?zoom=1 in my url after a btnzoomprevious & btnzoomnext is clicked.
<div id=zoomview class="view" style="left:100px;<%=isZoom?"":"display:none;" %>">
<div class="side">
<a id="btncloseview" class="btnview" style="left:-100px; top:60px;">close</a>
<a id="btnzoomprevious" class="btnzoomprevious" href="<%=ResolveClientUrl("~/" + gender + "/" + category + "/" + character + "/")%><%=prevproductName%><%=Request.Url.Query%>?zoom=1" style="margin:420px 0 0 -100px; display:<%=statusprev%>"></a>
<a id="btnzoomnext" class="btnzoomnext" href="<%=ResolveClientUrl("~/" + gender + "/" + category + "/" + character + "/")%><%=nextproductName%><%=Request.Url.Query%>?zoom=1 " style="margin:420px 0px 0 810px; display:<%=statusnext%>"></a>
</div>
<%if(!isZoom) {%>
<img src="<%=productImagesPath + prevproductImageZoom %>.jpg" id="mainImage" alt="Main Image" style="height:800px; width:800px;"/>
<img src="<%=productImagesPath + nextproductImageZoom %>.jpg" id="mainImage" alt="Main Image" style="height:800px; width:800px;"/>
<%}else {%>
<img data-src="<%=productImagesPath + productImageZoom %>.jpg" id="mainImage" alt="Main Image" style="height:800px; width:800px;">
<%} %>
</div>
I can't use the method in asp, because the ?zoom=1 is appending again again. I need to remove the room once the btncloseview is clicked.
What are you trying to do? Are you just trying to append the query to the url in the window? It could be something like this:
<script type='text/javascript'>
$("#btnzoomprevious").on("click", function() {
if (window.location.href.indexOf('?zoom=1') == -1) {
window.location.href = window.location.href + '?zoom=1';
}
});
$("#btnzoomnext").on("click", function() {
if (window.location.href.indexOf('?zoom=1') == -1) {
window.location.href = window.location.href + '?zoom=1';
}
});
$("#btncloseview").on("click", function() {
if (window.location.href.indexOf('?zoom=1') != -1) {
window.location.href = window.location.href.substring(0, window.location.href.indexOf('?zoom=1'));
}
});
</script>
However, this would cause the page to reload. If you are looking for a solution where the page does not reload, you can find more information here:
http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/
The short version of the article is, you can implement the following function:
window.history.pushState("object or string", "Title", "/new-url");
So, you could do something like this:
<script type='text/javascript'>
var urlPath = '';
$("#btnzoomprevious").on("click", function() {
if (window.location.href.indexOf('?zoom=1') == -1) {
urlPath = window.location.href + '?zoom=1';
window.history.pushState("","", urlPath);
}
});
$("#btnzoomnext").on("click", function() {
if (window.location.href.indexOf('?zoom=1') == -1) {
urlPath = window.location.href + '?zoom=1';
window.history.pushState("","", urlPath);
}
});
$("#btncloseview").on("click", function() {
if (window.location.href.indexOf('?zoom=1') != -1) {
urlPath = window.location.href.substring(0, window.location.href.indexOf('?zoom=1'));
window.history.pushState("","", urlPath);
}
});
</script>
You can find David Murdoch's original post about updating a URL without reloading the page here for more info: David's Post
Good Luck!
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();
}
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 )