Asynchronous output to textbox in asp.net - c#

I've got a foreach loop running in C# asp.net project which is run on server side.
After every iteration of the loop is complete i would like to update a textbox (consolebox.text) on the client web browser so the user can see that a loop has completed.
It only updates the textbox after the function is complete so the user doesn't see the progress output till the whole foreach is completed. Below is my code, i've tried ajax updatepanels to no avail
protected void Button1_Click(object sender, EventArgs e)
{
consolebox.Text = "Please Wait........"+ Environment.NewLine;
foreach (var listBoxItem in serverlist.Items)
{
string send = listBoxItem.ToString();
DELETEPROFILE(send);
consolebox.Text += ("" + send + "........Complete" + Environment.NewLine);
}
}

you can do it by web service. Use ajax to start functioning and other service to read functioning.
Sample:
Aspx
<script type = "text/javascript">
function ajaxCall(fsMathod) {
$.ajax({
type: "POST",
url: "Test.aspx/" + fsMathod,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
var TheTextBox = document.getElementById("<%=consolebox.ClientID%>");
TheTextBox.value = TheTextBox.value + response.d;
}
</script>
<body>
<form id="form1" runat="server">
<div style="margin:0 auto; width:20%">
Textbox: <asp:TextBox ID="consolebox" TextMode="MultiLine" runat="server"></asp:TextBox>
<br />
<input id="btnStartAsync" type="button" value="Start Async" onclick = "ajaxCall('startAsync');" />
<input id="btnReadAsync" type="button" value="Read Async" onclick = "ajaxCall('readAsync')" />
</div>
</form>
</body>
c#
static string CompletedItems = "";
[System.Web.Services.WebMethod]
public static string readAsync()
{
return "" + CompletedItems + "........Complete\n";
}
[System.Web.Services.WebMethod]
public static void startAsync()
{
asyncTask();
}
private static void asyncTask()
{
foreach (var listBoxItem in serverlist.Items)
{
string send = listBoxItem.ToString();
DELETEPROFILE(send);
//consolebox.Text += ("" + send + "........Complete" + Environment.NewLine);
CompletedItems += send + ",";
}
}

Related

How to perform searching in autofill on textbox with single enter press

<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" ></asp:TextBox>
</div>
<br>
<script type="text/javascript">
$(function fnc() {
$(".search_hot_txtbox").autocomplete({
source: function(request, response) {
$.ajax({
url: "hotel-result.aspx/BindDatatoDropdown",
data: "{ 'cn': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.HotelName
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
protected void chk3_CheckedChanged(object sender, EventArgs e)
{
if (Session["List"] != null)
UCPager1.GetItemsControl(1, 5, 0, chk3star.Checked, chk2star.Checked, chk1star.Checked, chk4star.Checked, chk5star.Checked, chkP1.Checked, chkP2.Checked, chkP3.Checked, chkP4.Checked, chkP5.Checked, txtHotel.Text, spP1.InnerText, spP2.InnerText, spP3.InnerText, spP4.InnerText, spP5.InnerText, new Repeater(), chkP6.Checked, chkP7.Checked, chkP8.Checked, spP6.InnerText, spP7.InnerText, spP8.InnerText);
else
UCPager1.GetItems();
}
You need here to make a post back, when you press "enter" on the textbox the browser make the postback, but if you wish to make it with javascript you need to fire up a button control.
So I place a button control, and I can even have it hidden with css as:
<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" onkeydown="return SendKeyEnterTo(event, 'btnGo');" />
<asp:Button runat="server" ID="btnGo" Text="search" onclick="btnSearch_Click" style="display:none;" ClientIDMode="Static" />
</div>
and then using this simple javascript I read the "enter" key from the textbox and trigger that post back of the input control.
function SendKeyEnterTo(e, IdToClick)
{
// look for window.event in case event isn't passed in
if (window.event)
{
e = window.event;
}
if (e.keyCode == 13)
{
document.getElementById(IdToClick).click();
return false;
}
else
{
return true;
}
}
This onkeydown="return SendKeyEnterTo(event, 'btnGo');" is important to read the text box input, and the ClientIDMode="Static" on the button is important to keep the same id when its rendered.
Also, please note, this code is run together with the autocomplete, and I have tested and use it.

Ajax.abort() not working

I have read a lot of pages explaining how ajax.abort() should work but for some reason I cannot get this to work with my situation. Here is the code I have:
<script type="text/javascript">
$(document).ready(function () {
...
function abortxhRequest() {
xhRequest.abort();
}
var xhRequest
function SendFileToServer(blob, fileName) {
if (xhRequest) {
xhRequest.abort();
}
xhRequest = $.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
//Do something with upload progress
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
progressBar.css("width", percentLoaded + '%');
progressPercentage.text(percentLoaded + '%');
}
}, false);
//Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
//Do something with download progress
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
progressBar.css("width", percentLoaded + '%');
progressPercentage.text(percentLoaded + '%');
}
}, false);
return xhr;
},
type: "POST",
url: "myPage.aspx/SendFileToServer",
data: "{blob: \"" + blob + "\", fileName: \"" + fileName + "\"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// If there was no data show No Data display
if (msg.d == "success") {
$("#spManagePhoto").html("Complete!");
setTimeout(function () {
$("#divManagePhotoTakePhoto").show();
$("#divManagePhotoUploading").hide();
}, 2000);
}
},
error: function (xhr, status, thrownError) { //Something went wrong on front side
alert(xhr.responseText); //You don't want to read all that, lol
//alert(thrownError); //Right down to the point
}
});
}
});
...
</script>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
...
<div id="divManagePhotoUploading">
<center>
<div class="marginTop10"><span id="spManagePhoto" class="SubmittingText"></span></div>
<div class="marginTop20"><img src="Images/ajax-loader.gif" alt="Loading..." /></div>
</center>
<div id="divProgressBarShell" class="ui-corner-all">
<div style="margin:5px; position:relative">
<div id="progress_bar">
<table border="0" cellpadding="0" cellspacing="0" style="width:100%; height:100%"><tr align="center"><td valign="middle">
<div class="percent"></div>
<label class="PercentLabel">0%</label>
</td></tr></table>
</div>
</div>
</div>
<div>
<button onclick="abortxhRequest();" class="nav-button2" style="display:block">Cancel Upload</button>
</div>
</div>
...
</asp:Content>
When I click the Cancel Upload button, ajax throws an error. Status of the error is "error" and xhr.responseText is blank. What am I doing wrong? Any help with this is greatly appreciated.
Abort() triggers the error() in Ajax. This is JQuery's standard behavior.
Do this to detect error but not abort:
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus != "abort") { // aborting actually triggers error with textstatus = abort.
alert(errorThrown.message);
}
}
Here is a reference of this behavior:
http://paulrademacher.com/blog/jquery-gotcha-error-callback-triggered-on-xhr-abort/

Response.Redirect does not change url c#

i am building asp .net website using jQuery and jQueryMobile framework. after succesfull login i am able to see contents of next page but the URL remains the same i.e. /Login.aspx
When i press F5 then only URL changes.
Login.aspx
<div data-role="content">
<form id="frmLogin" method="post" runat="server" action="Login.aspx">
<div data-role="fieldcontain">
<input type="text" name="txtUserName" id="txtUserName" placeholder="User Name" value="" runat="server" /><br />
<input type="password" name="txtUserPass" id="txtUserPass" placeholder="Password" value="" runat="server" />
<br />
<button id="cmdLogin" type="button">Login</button>
</div>
</form>
<div id="divDialog"></div>
</div>
JavaScript called when clicked on cmdLogin Login button
$('#cmdLogin').click(function () {
$.ajax({
url: 'ajaxExecute.aspx?Fn=VUSR',
type: 'POST',
context: document.body,
data: 'User=' + $('#txtUserName').val() + '&Pass=' + $('#txtUserPass').val(),
cache: false,
success: function (response) {
alert(f);
if (response == '1') {
f.submit();
}
else {
/*
Print Error
*/
}
}
});
});
Login Code Behind
Login.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
routeToDefaultPage();
}
}
private void routeToDefaultPage()
{
Response.Redirect("Piechart.aspx");
}
What is problem here ?
When i do inspect element after login successful (Contents of Piecharts.aspx but URL is Login.aspx) . i see following in head section
<base href="http://localhost:49712/Login.aspx">
Are you sure to have flag ispostback assigned to true when you click. A break point on this line could help you?
Try this:
Response.Redirect("Piechart.aspx");
Response.End();
What about jquery redirect after ajax call?
Try to add this after ajax call success. header( 'Location: Piechart.aspx' ); ?
$('#cmdLogin').click(function () {
$.ajax({
url: 'ajaxExecute.aspx?Fn=VUSR',
type: 'POST',
context: document.body,
data: 'User=' + $('#txtUserName').val() + '&Pass=' + $('#txtUserPass').val(),
cache: false,
success: function (response) {
// redirects page after login successful
header( 'Location: Piechart.aspx' );
alert(f);
if (response == '1') {
f.submit();
}
else {
/*
Print Error
*/
}
}
});
});
This works for me...!!
$.mobile.changePage( "/Piecharts.aspx", {
transition: "pop"
});

AutoPopulate DropDownList Using Ajax

I have 2 dropdownlist which is already binded on pageload , i want to rebind these two dropdownlist after firing a ajax function.Here i have written a sql server stored procedure to get the data which is needed to dropdownlists.But how i will get the value to dropdownlist,so that it can bind the new data using ajax function.The screen is developed by using Asp.net C# coding.
Here is the drop down list of the asp.net
<asp:DropDownList id="ddlCourse" runat="server" AutoPostBack="false"
Height="28px" title="Select Course" Width="290px"
></asp:DropDownList>
and here is the jquery method that is calling the web service method
function BindCourse() {
$.ajax({
type: "POST",
url: "/WebService/CollegeWebService.asmx/GetCourseDetails",
data: "{}",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCoursePopulated,
error: function (xml, textStatus, errorThrown) {
alert('error');
alert(xml.status + "||" + xml.responseText);
}
});
}
This is the method to That is used in the ajex call method and call the PopulateControl method to bind the Drop down List
function OnCoursePopulated(response) {
PopulateControl(response.d, $('#<%=ddlCourse.ClientID %>'));
}
Here is the description of the PopulateControl Method
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
Thus you finally bind the drop down list
You can try the following as a demo. Server side DropDownLists are replaced with HTML select elements so that exception "Invalid postback or callback argument" doesn't happen.
Drawback in this demo is that the values are not restored on form after postback. You can put this inside a form in Default.aspx:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function populate(populateInitial) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Default.aspx/populate',
data: "{'populateInitial': '" + populateInitial + "'}",
dataType: "json",
async: false,
success: function(result) {
var ddlItems = document.getElementById('ddlItems');
ddlItems.options.length = 0;
$.each(result.d, function(key, item)
{ ddlItems.options[key] = new Option(item); });
}
});
}
</script>
<form id="form1" runat="server">
<div>
<select id="ddlItems" name="ddlItems">
</select>
<br />
<input type="button" onclick="populate('0');" value="Change values" />
<br />
Selected item:
<asp:Label ID="lblSelectedItem" runat="server" Text=""> </asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
Text="Write out selected item text" />
</div>
<script type="text/javascript">
populate('1');
</script>
And you put these methods inside Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
lblSelectedItem.Text = Request["ddlItems"].ToString();
}
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> populate(string populateInitial)
{
if (populateInitial == "1")
return (new string[] { "a", "b" }).ToList();
else
return (new string[] { "c", "d", "e", "f" }).ToList();
}
You should make Ajax call to some sort of page (I advice you to add Generic Hanlder) which responses xml or json or even html, of drop down values and textfield values, than read it in javascript jquery and generate html for your drop down which is the following
<select id="ddl">
<option value="value">text</option>
</select>
you should read "value" & text and generate this> <option value="value">text</option>
and append to ddl

How to handle multiple callbacks in ASP.Net 4.0 C#? Example

I have to handle two callbacks in one page one on button event and other on List.
When button 'showDate' is clicked it display Time
and when button 'btnlookup' is clicked it show the respective value of listbox item.. below is my code HTML & .cs file
<head runat="server">
<title></title>
<script language="javascript">
function ReceiveResults(arg, context)
{
showDate.innerHTML = arg;
}
function LookUpStock() {
var lb = document.getElementById("ListBox1");
var product = lb.options[lb.selectedIndex].text;
CallServer2(product, "");
}
function ReceiveServerData(rValue) {
document.getElementById("ResultsSpan").innerHTML = rValue;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="showDate">aaa</span>
</br>
<input id="btnShowDate" type="button" value="getDate" onclick="CallServer();"/>
</div>
<div>
<asp:ListBox ID="ListBox1" Runat="server"></asp:ListBox>
<br />
<br />
<button type="btnLookUP" onclick="LookUpStock()">Look Up Stock</button>
<br />
<br />
Items in stock: <span id="ResultsSpan" runat="server"></span>
<br />
</div>
</form>
</body>
Code for .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class callback : System.Web.UI.Page, ICallbackEventHandler
{
protected String returnValue;
protected String myDate;
protected System.Collections.Specialized.ListDictionary catalog;
public String GetCallbackResult()
{
//return returnValue;
return myDate;
}
public void RaiseCallbackEvent(String eventArgument)
{
myDate = System.DateTime.Now.ToLongTimeString();
//if (catalog[eventArgument] == null)
//{
// returnValue = "-1";
//}
//else
//{
// returnValue = catalog[eventArgument].ToString();
//}
}
protected void Page_Load(object sender, EventArgs e)
{
//For Time
ClientScriptManager cSM = Page.ClientScript;
String myCBRefrence = cSM.GetCallbackEventReference(this, "arg", "ReceiveResults", "context");
cSM.RegisterClientScriptBlock(this.GetType(), "CallServer", "function CallServer(arg, context) {" + myCBRefrence + ";}", true);
//callback back for listbox
//String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
//String callbackScript = "function CallServer2(arg, context){ " + cbReference + ";}";
//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer2", callbackScript, true);
//catalog = new System.Collections.Specialized.ListDictionary();
//catalog.Add("monitor", 12);
//catalog.Add("laptop", 10);
//catalog.Add("keyboard", 23);
//catalog.Add("mouse", 17);
//ListBox1.DataSource = catalog;
//ListBox1.DataTextField = "key";
//ListBox1.DataBind();
}
}
Code which is comments is for the second callback event, Problem is in this code is that i can only raise one callback, can someone tell me what changes i need to make in code so that i can raise both callback event.
This is a piece of personal advice: do not write JavaScript in your C# code. This will get very messy and very hard to debug quickly.
If you really need to get this information, you should use an ASP.NET Web Service (a .asmx file). You can call these Web Services using JavaScript or jQuery (I prefer jQuery myself).
If I had a .asmx file like so:
[System.Web.Script.Services.ScriptService]
public class ServerTime : System.Web.Services.WebService
{
[WebMethod]
public string Get()
{
return System.DateTime.Now.ToLongTimeString();
}
}
I would call that using the following jQuery code:
$.ajax({ type: "POST", dataType: "json", contentType: "application/json; charset=utf-8",
url: "ServerTime.asmx/Get",
success: function (result) {
$("#showDate").html(result.d);
}
});
Note that success is deprecate din the latest version of jQuery, but I can't find a good example of done online.

Categories

Resources