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!
Related
I want to check unchecked checkbox in based on data-id.
On drop down change i want to check unchecked checkbox in jstree.
I am Providing MY controller and Ajax Method bellow.
This is my jstree view.
Here is My Controller :
[HttpPost]
public ActionResult GetSingleUser(int id)
{
MachineShopDBEntities DB = new MachineShopDBEntities();
var SPresult = DB.GetSingleUser(id).FirstOrDefault();
return Json(SPresult);
}
Here is my Script:
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
$('.jstree-container-ul li[data-id=' + (i + 1) + ']').find('.jstree-anchor').addClass('jstree-clicked');
}
}
});
});
Here I created demo for you.
Make changes according to code snippet below
jQuery(function ($) {
$('.menux').jstree({
"core": { "check_callback": false },
"checkbox": { "keep_selected_style": false, "three_state": false, "tie_selection": false, "whole_node": false, },
"plugins": ["checkbox"]
}).bind("ready.jstree", function (event, data) {
$(this).jstree("open_all");
}).on("check_node.jstree uncheck_node.jstree", function (e, data) {
var currentNode = data.node;
var parent_node = $(".menux").jstree().get_node(currentNode).parents;
if (data.node.state.checked)
$(".menux").jstree().check_node(parent_node[0]);
else
$(".menux").jstree().uncheck_node(parent_node[0]);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.css" rel="stylesheet" />
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/jstree.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<div class="menux">
<ul>
<li>
Root node 1
<ul>
<li data-id="1"><a href="#" >Child node 1</a> </li>
<li data-id="2"><a href="#" >Child node 2</a></li>
<li data-id="3"><a href="#" >Child node 3</a></li>
<li data-id="4"><a href="#" >Child node 4</a></li>
<li data-id="24"><a href="#" >Child node 24</a></li>
</ul>
</li>
</ul>
</div>
Edit:
First make sure you have disable three-state while initializing jsTree as mentioned in above code snippet.
Try to implement above $('.menux li').each function in your code.
The below code is only sample to where you have to put this $('.menux li').each.
$("#UserSelect").change(function () {
$.post("/MenuMaster/GetSingleUser?id=" + $(this).val(),
function (data, status) {
var databaseString = data.MenuEnable;
$('.menux li').each(function (index, value) {
var node = $(".menux").jstree().get_node(this.id);
var id = node.data.id;
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
if ((i + 1) == id) {
$(".menux").jstree().check_node(this.id);
}
}
}
});
});
});
If you got any error like jsTree is not a function then you can replace above $('.menux li').each function with this
$('.menux li').each(function (index, value) {
for (i = 0; i <= databaseString.length; i++) {
if (databaseString.substring(i, i + 1) == "1") {
var dataid = $('#' + this.id).data('id');
if ((i + 1) == dataid) {
$('#' + this.id).find('.jstree-anchor').addClass('jstree-clicked');
}
}
}
});
I am adding some html/css in div.InnerHtml by applying foreach loop reading each directory contents to post images, and i want to call function showfile(dynamic parameter) into it.
how should i do this?
the showfiles(dynamic parameter) function is working fine, but i want to make it work after user clicks the controls generated in div, which is not working, please have a look on my code and give me suggestion.
public void Showimages( string fname)
{
string name = Path.GetFileName(fname); //select only name.ext
str2 = "<div style='max-width:250px; max-height:170px;'>"
+ "<a href ='" + filepath2 + "/" + name + "' >"
+ "<img class='img-responsive' src='" + filepath2 + "/" + name + "'>"+name+"</a></div>"; //post image + name in loop
imgcontainer.InnerHtml += str2;
}
public void Generatecontrol(string dp)
{
//linkdiv.InnerHtml += "<asp:LinkButton runat='server' class='linkb' OnClick='Showfiles(" + dp.ToString()+ ")' >" + dp.ToString() + "</asp:LinkButton><br />";
linkdiv.InnerHtml += "<span class='col-lg-4'><asp:LinkButton runat='server' class='col-lg-4 linkb' OnClick='Showfiles' CommandArgument=" + dp.ToString()+ " ><img src='/pimages/folder.jpg' height='75' width='75' border='0'/><br />" + dp.ToString() + "<br /></asp:LinkButton></span>";
}
See you are passing the value as CommandArgument, so you have to take the same from CommandArgument. Change the signature of Showimages like the following:
public void Showimages(object sender, CommandEventArgs e)
{
string name = Path.GetFileName(e.CommandArgument.ToString());
// your code here
}
Pritesh,
If your main concern is only displaying images dynamically, then you can use jquery, here below I prepared a small snippet, please look at once,
Backend code:
public List<string> GetImages()
{
string fileName = "";
string[] files = System.IO.Directory.GetFiles("");
List<string> listImages = new List<string>();
foreach (string file in files)
{
fileName = System.IO.Path.GetFileName(file);
listImages.Add(fileName);
}
return listImages;
}
HTML:
<div class="row" style="margin-top:20px;">
<div id="imgPreview"></div>
</div>
<button id="btnShowImage" onclick="ShowImages()">Show Image</button>
Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function ShowImages() {
$("#imgPreview").html("");
$.ajax({
type: 'post',
url: '/xyz/GetImages',
data: formData,
success: function (response) {
if (response != null) {
var imageList =DisplayImages(response);
$("#imgPreview").append(imageList);
}
},
processData: false,
contentType: false,
error: function () {
alert("Whoops something went wrong!");
}
});
}
)};
function DisplayImages(data) {
var imageDiv ="";
if (data != null) {
$.each(data, function (index, value) {
//This is for dynamically generating image div. You can manipulate this section as per you need.
imageDiv = "<div style='max-width:250px; max-height:170px;'>";
imageDiv += "<a href ='~/your static path/" + value + "' >";
imageDiv += "<img class='img-responsive' src='='~/your static path/" + value + "'>" + value + "</a></div>";
});
}
return imageDiv;
}
</script>
Let me know if it helped.
I have a form on which I am adding rows dynamically using Jquery.
Please take a look: DEMO
Now I want to save the data of all rows that has been added in my database using Jquery Ajax call on click event of SAVE button. The point where I am stuck is .. I am not sure how should I extract data of all rows and send it to the webmethod. I mean had it been c# I could have used a DataTable to store data of all rows before sending it to DataBase. I think I should create a string seperated by commas and pipe with data of each row and send it to webmethod. I am not sure if its the right approach and also how this is to be done (ie. creating such a string).
HTML
<table id="field">
<tbody>
<tr id="row1" class="row">
<td> <span class='num'>1</span></td>
<td><input type="text" /></td>
<td><select class="myDropDownLisTId"> <input type="text" class="datepicker" /></select></td><td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">Add Field</button>
<button type="button" id="deleteField">Delete Field</button>
<button type="button" id="btnsave">SAVE</button>
2 suggestions:
To keep it as close as what you already have, you could just enclose your table in a form tag, and then you could just submit the form (use something like the jQuery Form plugin to submit it via Ajax). The trickiest part will be to bind that data to action parameters. You may be able to receive it in the form of an array, or you could default to looping through properties of the Request.Form variable. Make sure you generate proper names for those fields.
I think the cleanest way to do it would be to have a JavaScript object holding your values, and having the table generated from that object, with 2-way bindings. Something like KnockoutJS would suit your needs. That way the user enters the data in the table and you'll have it ready to be Json-serialized and sent to the server. Here's a quick example I made.
I wouldn't recommend that approach, but if you wanted to create your own string, you could do something along those lines:
$("#btnsave").click(function () {
var result = "";
$("#field tr").each(function (iRow, row) {
$("td input", row).each(function (iField, field) {
result += $(field).val() + ",";
});
result = result + "|";
});
alert(result);
});
You will have problems if the users types in a comma. That why we use well known serialization formats.
use ajax call on save button event...
like this
$(document).ready(function () {
$('#reqinfo').click(function () {
// debugger;
var emailto = document.getElementById("emailid").value;
if (emailto != "") {
$.ajax({
type: "GET",
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto,
// data: dat,
Accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// debugger;
},
error: function (result) {
// debugger;
}
});
}
else {
//your validation message goes here
return false;
}
});
});
and add you all data in quesry string and transfer it to webservice..
url: "/EmailService1.svc/EmailService1/emaildata?Email=" + emailto + "data1=" + data1,
<script type="text/javascript">
var _autoComplCounter = 0;
function initialize3(_id) {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}
google.maps.event.addDomListener(window, 'load', initialize3);
function incrementValue() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
function GetDynamicTextBox(value) {
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
return '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "' + value + '" onkeypress = "calcRoute();" />' +
'<input type="button" class="superbutton orange" value="Remove" onclick = "RemoveTextBox(this)" />'
}
function AddTextBox() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
if (document.getElementById('number').value < 3) {
document.getElementById('number').value = value;
var div = document.createElement('DIV');
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var ht = '<input name = "DynamicTextBox" type="text" id="' + _id + '" value = "" onkeypress = "calcRoute();" class="clsgetids" for-action="' + _id + '" />' +
'<input type="button" class="superbutton orange" value="#Resources.SearchOfferRides.btnRemove" onclick = "RemoveTextBox(this); calcRoute();" />';
div.innerHTML = ht;
document.getElementById("TextBoxContainer").appendChild(div);
setTimeout(function () {
var input_TO = document.getElementById(_id);
var options2 = { componentRestrictions: { country: 'ID' } };
new google.maps.places.Autocomplete(input_TO, options2);
}, 100);
document.getElementById("TextBoxContainer").appendChild(div);
}
else {
alert('Enter only 3 stop point. !!');
}
}
function RemoveTextBox(div) {
//calcStopPointRoute();
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value--;
document.getElementById('number').value = value;
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
// window.onload = RecreateDynamicTextboxes;
</script>
And get the value from textbox:
#region stop point
string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
if (textboxValues != null)
{
for (Int32 i = 0; i < textboxValues.Length; i++)
{
if (textboxValues.Length == 1)
{
model.OptionalRoot = textboxValues[0].ToString();
}
else if (textboxValues.Length == 2)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
}
else if (textboxValues.Length == 3)
{
model.OptionalRoot = textboxValues[0].ToString();
model.OptionalRoot2 = textboxValues[1].ToString();
model.OptionalRoot3 = textboxValues[2].ToString();
}
else
{
model.OptionalRoot = "";
model.OptionalRoot2 = "";
model.OptionalRoot3 = "";
}
}
}
#endregion
Short answer:
DataTable equivalent in javascript is Array of custom object (not exact equivalent but we can say that)
or
you roll your own DataTable js class which will have all the functions and properties supported by DataTable class in .NET
Long answer:
on client side(aspx)
you define a class MyClass and store all your values in array of objects of that class
and then pass that array after stingyfying it to web method
JSON.stringify(myArray);
on the server side(codebehind)
you just define the web method to accept a list of objects List<MyClass>
PS: When calling web method, Asp.net automatically converts json array into List<Object> or Object[]
Loooong answer (WHOLE Solution)
Page aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="App_Themes/SeaBlue/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
function MyClass(title,option,date) {
this.Title = title;
this.Option = option;
this.Date = date;
}
function GetJsonData() {
var myCollection = new Array();
$(".row").each(function () {
var curRow = $(this);
var title = curRow.find(".title").val();
var option = curRow.find(".myDropDownLisTId").val();
var date = curRow.find(".datepicker").val();
var myObj = new MyClass(title, option, date);
myCollection.push(myObj);
});
return JSON.stringify(myCollection);
}
function SubmitData() {
var data = GetJsonData();
$.ajax({
url: "testForm.aspx/PostData",
data: "{ 'myCollection': " + data + " }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Success");
}
});
}
$(document).ready(function () {
filldd();
CreateDP();
var rowstring = "<tr class='row'><td class='number'></td><td><input type='text' class='title'/></td><td><select class='myDropDownLisTId'/><input type='text' class='datepicker'/></td><td><input type='submit'></input></td></tr>";
$("#addField").click(function (event) {
$("#field tbody").append(rowstring);
filldd();
CreateDP();
if ($("td").hasClass("number")) {
var i = parseInt($(".num:last").text()) + 1;
$('.row').last().attr("id", "row" + i);
$($("<span class='num'> " + i + " </span>")).appendTo($(".number")).closest("td").removeClass('number');
}
event.preventDefault();
});
$("#deleteField").click(function (event) {
var lengthRow = $("#field tbody tr").length;
if (lengthRow > 1)
$("#field tbody tr:last").remove();
event.preventDefault();
});
$("#btnsave").click(function () {
SubmitData();
});
});
function filldd() {
var data = [
{ id: '0', name: 'test 0' },
{ id: '1', name: 'test 1' },
{ id: '2', name: 'test 2' },
{ id: '3', name: 'test 3' },
{ id: '4', name: 'test 4' },
];
for (i = 0; i < data.length; i++) {
$(".myDropDownLisTId").last().append(
$('<option />', {
'value': data[i].id,
'name': data[i].name,
'text': data[i].name
})
);
}
}
function CreateDP() {
$(".datepicker").last().datepicker();
}
$(document).on('click', 'input[type="submit"]', function () {
alert($(this).closest('tr')[0].sectionRowIndex);
alert($(this).closest('tr').find('.myDropDownLisTId').val());
});
</script>
</head>
<body>
<form id="frmMain" runat="server">
<table id="field">
<tbody>
<tr id="row1" class="row">
<td>
<span class='num'>1</span>
</td>
<td>
<input type="text" class="title"/>
</td>
<td>
<select class="myDropDownLisTId">
</select>
<input type="text" class="datepicker" />
</td>
<td>
<input type="submit"></input>
</td>
</tr>
</tbody>
</table>
<button type="button" id="addField">
Add Field</button>
<button type="button" id="deleteField">
Delete Field</button>
<button type="button" id="btnsave">
SAVE</button>
</form>
</body>
</html>
CodeBehind:
public partial class testForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void PostData(List<MyClass> myCollection)
{
Console.WriteLine(myCollection.Count);
}
}
public class MyClass
{
string title;
public string Title
{
get { return title; }
set { title = value; }
}
string option;
public string Option
{
get { return option; }
set { option = value; }
}
string date;
public string Date
{
get { return date; }
set { date = value; }
}
}
Hope this helps
References:
Json2.js file
stringify method
define a class in js
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 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..