I'm working in ASP.Net 4. I have the following within the body tag of my aspx:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"/>
<script type="text/javascript">
function Process() {
var CHK = document.getElementById("<%=lstAffEmployees.ClientID%>");
var checkbox = CHK.getElementsByTagName("input");
var counter = 0;
for (var i = 0; i < checkbox.length; i++) {
if (checkbox[i].checked) {
counter++;
var Attorney = label[i].innerHTML;
var cutoff = Attorney.indexOf('[');
var cAttorney = Attorney.substring(0, cutoff - 1);
PageMethods.saveData(checkbox[i].value, cAttorney);
}
}
return true;
}
</script>
In my code-behind, I have:
[WebMethod]
public static void saveData(string attyNo, string attyName)
{
//mycode
}
In debugging, I get to the PageMethods call in the javascript, but then saveData in my code-behind is never called. I don't understand why not. Can anyone help?
Related
I need to get a list of innerHTML strings from a website (for example facebook) to my .NET application.
Is there a way to get results from the following function into my application (i would put this data into a list) :
var data = new Array();
for(i=0; i<document.getElementsByClassName("class-name").length;i++)
data.push(document.getElementsByClassName("class-name")[i].innerHTML);
The code above outputs exactly the data i need, now my question is if it's possible to somehow get this data into my c# list?
This is how I'd like it to look :
var JS_DATA = data; //get the js array as a variable
static List<string> data = new List<string>(); //make a new list
foreach (string str in JS_DATA)
data.Add(String.Format("{0}", str)); //add the whole js array to the list
Here is an example:
see hidden Field array_store
Client side:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var array_store;
window.onload = function () {
array_store = document.getElementById("array_store");
document.getElementById("array_disp").innerHTML = array_store.value;
};
function UpdateArray() {
var arr;
if (array_store.value == "") {
arr = new Array();
} else {
arr = array_store.value.split(",");
}
arr.push((arr.length + 1).toString());
array_store.value = arr.join(",");
};
</script>
</head>
<body>
<form id="form1" runat="server">
<span id="array_disp"></span>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="UpdateArray()" />
<input type="hidden" id="array_store" name = "ArrayStore" value = '<%=this.ArrayStore %>' />
</form>
</body>
</html>
C#:
protected string ArrayStore = "";
protected void Page_Load(object sender, EventArgs e)
{
this.ArrayStore = Request.Form["ArrayStore"];
}
Hello I am trying to implement a timer in c sharp that counts seconds and display it on my html page. But when i pass the variable to javascript it is always 0. I have searched everywhere for an answer.
This is my code so far:
The timer object:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
/// <summary>
/// Summary description for Class1
/// </summary>
public class TimerEu
{
private Timer t;
private int time;
public TimerEu()
{
this.t = new Timer(1000);
this.time = 0;
t.Elapsed += new ElapsedEventHandler(RunEvent);
t.Interval = 1000;
t.Enabled = true;
}
public void RunEvent(object source, ElapsedEventArgs e)
{
this.time++;
Console.WriteLine(time);
}
public int getTime()
{
return this.time;
}
}
aspx.cs page:
public partial class _Default : System.Web.UI.Page
{
public String[] var=new String[10];
public TimerEu time;
public int testint;
protected void Page_Load(object sender, EventArgs e)
{
time = new TimerEu();
testint = 0;
Console.Write("hello"+time.getTime());
for (int i = 0; i < 10; i++)
var[i] =Operations.test.convertString();
}
public void plus()
{
this.testint++;
}
}
and the html/javascript part:
<form id="form1" runat="server">
<div>
<br></br>
<br></br>
<br></br>
<p id="demo" runat="server"></p>
<script>
var now=0;
var x= setInterval(function () {
//now++;
now = <%=time.getTime()%>
// now =<%=testint%>
// <%plus();%>
document.getElementById("demo").innerHTML = now;
},1000)
</script>
The problem is that the javascript dosen't seem to call the getTime function every sec, instead it only gets 0 as output. What am I doing wrong?
You have to understand important thing. This statement <%=time.getTime()%> is executed only once on the server side before rendered html page is sent to the browser. When it's executed, it will be replaced with 0 (the result of method call).
Browser will see only now = 0 and in this case, javascript code doesn't make any sense
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var before_loadtime = new Date().getTime();
window.onload = Pageloadtime;
function Pageloadtime() {
var aftr_loadtime = new Date().getTime();
// Time calculating in seconds
pgloadtime = (aftr_loadtime - before_loadtime) / 1000
document.getElementById("loadtime").innerHTML = "Pgae load time is <font color='red'><b>" + pgloadtime + "</b></font> Seconds";
}
</script>
</head>
<body>
<h3 style="font-weight: bold; font-style: italic; font-size: large; color: #3333CC">Page load time in JavaScript</h3>
<div>
<span id="loadtime"></span>
</div>
</body>
</html>
I am try to automatically fire a sub routine with with a javascript "document.getElementById('button2').click();" as it is in the below code. Can someone please help me see why the code is not working. Thank you
<%# Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" debug = "true"%>
<%# Import Namespace="System.Data.SqlClient"%>
<%# Import Namespace="System.Data"%>
<script language="vb" runat="server">
Sub sendmsg(sender As Object, e As EventArgs)
response.Redirect("index.aspx")
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function Confirm() {
var str = $('#loutput').val(); //'We are inviting you for s special business meeting on Tueday, at No 12, Fred street. for more information please call 02341123333';
var updateString = function(input_text) {
//1. Find consecutive 11 numeric digits
var match = input_text.match(/\d{11}/);
//2. divide it into a string of 3s separated by space
var new_str = '';
for (var i = 1; i < match[0].length + 1; i++) {
new_str = new_str + match[0][i - 1];
if (i > 1 && i % 3 == 0)
new_str = new_str + ' ';
}
//3. Replace old match no. with the new one
console.log(match)
if (match[0] != '')
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
confirm_value.value = "Yes";
input_text = input_text.replace(match[0], new_str)
$('#loutput').val(input_text);
confirm2()
//document.getElementById('loutput').innerHTML = input_text;
} else {
confirm_value.value = "No";
confirm2()
}
$('#loutput').val(input_text);
//document.getElementById('loutput').innerHTML = input_text;
};
updateString(str);
};
function confirm2() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(" send the message now?")) {
confirm_value.value = "Yes";
document.getElementById('button2').click();
//document.getElementById('loutput').innerHTML = input_text;
} else {
confirm_value.value = "No";
}
//document.getElementById('loutput').innerHTML = input_text;
};
</script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<form runat="server" action="formatmessage3.aspx" method="post">
<input type="texarea" id="loutput" name="loutput" value="<%=request.form ("loutput") %>" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>
<asp:button ID="button2" OnClick="sendmsg" Text="send" runat="server" />
</form>
</body>
</html>
The problem here is the fact you are using a .NET button with runat="server" so it is going to change the id of the button to a different value.
<asp:button ID="button2" OnClick="sendmsg" Text="send" runat="server" />
You either have to reference the element by a class
document.getElementsByClassName("myClass")[0].click();
or reference the dynamic name
document.getElementById("<%= button2.ClientID %>").click();
or in .NET4 you can use ClientIDMode="Static"
I've created an User Control where I have a button. And when this button is clicked a jquery function is executed. The jquery function is inside the User Control page.
Now i'm trying to add this User Control dynamically in my page, inside an UpdatePanel.
The problem is that my button is not working.
After i google it, i found out that maybe the problem is in using jquery inside ajax UpdatePanel. After every asynchronous postback the jquery script is lost. So the idea is to rebind my jquery function in every asyn postback. But in the all answers that i found, they kinda suppose that the script manager is in User control and it's not in my case.
Here my jquery fucntion
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#<%= idButtonLeft %>").bind("click", function () {
var options = $("#<%= idListDestinataire %> option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("#<%= idListSource %>").append(opt);
}
});
$("#<%= idButtonRight %>").bind("click", function () {
var options = $("#<%= idListSource %> option:selected");
for (var i = 0; i < options.length; i++) {
var opt = $(options[i]).clone();
$(options[i]).remove();
$("#<%= idListDestinataire %>").append(opt);
}
});
});
</script>
the code to add my User control dynamically
Dim CListBox As UserControl = LoadControl("DragDropList.ascx")
CListBox.ID = "CListBox" + i.ToString()
CType(CListBox, DragDropList).idListSource = "ListLeft" + i.ToString()
CType(CListBox, DragDropList).idListDestinataire = "ListRight" + i.ToString()
CType(CListBox, DragDropList).idButtonLeft = "idButtonLeft" + i.ToString()
CType(CListBox, DragDropList).idButtonRight = "idButtonRight" + i.ToString()
UpdatePanel1.ContentTemplateContainer.Controls.Add(CListBox)
Panel1.Controls.Add(CListBox)
in my page i have this
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ImageButton1" />
</Triggers>
</asp:UpdatePanel>
<asp:ImageButton ID="ImageButton1" ImageAlign="Right" EnableViewState="false" ImageUrl=".\image\ajouter.png" runat="server" AlternateText="Ajouter" OnClick="AjouterC"/>
So please any ideas to help.
Thank you
When i changed the trigger on PostBackTrigger, it's working but i want it in asynchrone postback. and still don't know why it's not working!
Use This
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
$(function () {
//Your script
});
}
}
</script>
This will work on post back that your update panel is giving to you.
Project doesn't need any javascript libraries such as jQuery, Dojo, Prototype so there is no easy way i suppose. I would like to have in-depth answers for the question explaining how would one do this. As most of you might know asp.net checkboxlist emits a markup like below in Flow repeatLayout.
<span>
<checkbox><label></br>
<checkbox><label></br>
<checkbox><label></br>
</span>
i haven't put the ending/closing tags for simplicity. We have a textbox for searching through this list of checkbox.Now comes the question,
How would i Filter the checkboxlist when user types the search term in the textbox and hide the unmatched checkbox+label.
some more questions i would like getting answers for that are related to above
Is there any ready made STANDALONE script for this purpose?
Is there a pattern , article, post explaining the glitches, points to remember while providing search functionality? something like onkeydown don't do this,
My Idea right now would be have a cached collection of label tags innerHTML then loop through each tag and check for search term, when found hide all others but show only matching.[My Concern is what will happen when list is too long, on every keypress looping is not the best idea i suppose]
Your suggestions, answers, solution, scripts are welcome
This solution is based on Ktash's answer. I made it cause I want to learn more about javascript, DOM navigating and RegExp.
I changed "keypress" event with "keydown" since the previous doesn't trigger on backspace/delete so deleting all the characters with backspace/delete still left the list filtered.
[Default.aspx]
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RealtimeCheckBoxListFiltering.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
window.onload = function () {
var tmr = false;
var labels = document.getElementById('cblItem').getElementsByTagName('label');
var func = function () {
if (tmr)
clearTimeout(tmr);
tmr = setTimeout(function () {
var regx = new RegExp(document.getElementById('inputSearch').value);
for (var i = 0, size = labels.length; i < size; i++)
if (document.getElementById('inputSearch').value.length > 0) {
if (labels[i].textContent.match(regx)) setItemVisibility(i, true);
else setItemVisibility(i, false);
}
else
setItemVisibility(i, true);
}, 500);
function setItemVisibility(position, visible)
{
if (visible)
{
labels[position].style.display = '';
labels[position].previousSibling.style.display = '';
if (labels[position].nextSibling != null)
labels[position].nextSibling.style.display = '';
}
else
{
labels[position].style.display = 'none';
labels[position].previousSibling.style.display = 'none';
if (labels[position].nextSibling != null)
labels[position].nextSibling.style.display = 'none';
}
}
}
if (document.attachEvent) document.getElementById('inputSearch').attachEvent('onkeypress', func); // IE compatibility
else document.getElementById('inputSearch').addEventListener('keydown', func, false); // other browsers
};
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:TextBox runat="server" ID="inputSearch" ClientIDMode="Static" />
</td>
</tr>
<tr>
<td>
<asp:CheckBoxList runat="server" ID="cblItem" ClientIDMode="Static" RepeatLayout="Flow" />
</td>
</tr>
</table>
</form>
</body>
</html>
[Default.aspx.cs]
using System;
using System.Collections.Generic;
namespace RealtimeCheckBoxListFiltering
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
cblItem.DataSource = new List<string>() { "qwe", "asd", "zxc", "qaz", "wsx", "edc", "qsc", "esz" };
cblItem.DataBind();
}
}
}
var tmr = false;
var labels = document.getElementsByTagName('label')
var func = function() {
if (tmr) clearTimeout(tmr);
tmr = setTimeout(function () {
var regx = new Regex(inputVal); /* Input value here */
for(var i = 0, size = labels.length; i < size; i++) {
if(regx.match(labels[i].textContent || labels[i].innerText)) labels[i].style.display = 'block';
else labels[i].style.display = 'none';
}
}, 100);
}
if (document.attachEvent) inputField.attachEvent('onkeypress', func);
else inputField.addEventListener('keypress', func, false);
Not perfect, and not all the way complete, but it should get you started on it. There is a 100 millisecond delay before it performs the loop so that it won't run on every keypress, but likely just after they've stopped typing. Probably want to play with the value a bit as you see fit, but it gives you the general idea. Also, I didn't set the variables for inputField nor inputVal, but those I assume you would already know how to grab. If your labels are not a static list onload, you'll probably want to get the list every time.