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

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.

Related

can not get data form function using ajax jquery in asp.net c#

i am trying use $.ajax() method in asp.net to fill a html tag but i didn't get any data from on success parameter
i am calling getData function from c# code and I tried to return a string but it doesn't work i also tried to user Response.write() but the same issue
when I alert returned value it show me the aspx page code
as following image
here is my code
Default.apsx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#firstDrop").on("change", function () {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
data: { id: $("#firstDrop").val() },
success: function (data) {
alert(data);
$("#secondDrop").html(data);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select runat="server" id="firstDrop">
<option value="0">first select</option><option value="1">second select</option><option value="3">third select</option>
</select>
<select id="secondDrop"></select>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string getData()
{
return"<option>ABC</option><option>CDE</option>";
}
}
Basic rule when creating a webmethod in asp.net.
Your method should be static.
You need to decorate your function with System.Web.Services.WebMethod.
C# Code Behind
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Javascript (Aspx)
Here, in your case make your getdata function static and webmethod as well. When calling the webmethod through ajax use data.d to read the response.
[System.Web.Services.WebMethod]
public static string getData(int id)
{
return "<option>ABC</option><option>CDE</option>";
}
$("#firstDrop").on("change", function() {
$.ajax({
url: "Default.aspx/getData",
type: "POST",
dataType: "json",
data: {
id: $("#firstDrop").val()
},
success: function(data) {
alert(data.d);
$("#secondDrop").html(data.d);
}
});
});
Reference Site:
https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Similar thread "Calling webmethod in webform"
calling-a-webmethod-with-jquery-in-asp-net-webforms

Jquery Ajax send formdata to asp.net webpage (aspx.cs)

Below is the my ajax request
function sendData() {
var formdata = new FormData();
var fileUpload = $("#txtUploadFile").get(0);
var files = fileUpload.files;
for (var i = 0; i < files.length; i++) {
formdata.append(files[i].name, files[i]);
}
formdata.append("PaymentDate", new Date());
$.ajax({
url: 'CCA_Form.aspx/SendData',
type: 'POST',
data: formdata,
contentType: false,
processData: false,
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
}
and my server method is like this
[WebMethod]
public static string SendData()
{//break point here
// code
return "return data";
}
the ajax method always showing success message and webmethod not hitting in server side. Could you help me what i missed in my code?
Thanks in advance.
Add a scriptmanager into your page with EnablePageMethods="True"
In C#:
[WebMethod]
public static string SendData(DateTime date)
{//break point here
// code
return "return data";
}
In aspx
<asp:ScriptManager ID="ScriptManagerMain"
runat="server"
EnablePageMethods="true"
ScriptMode="Release"
LoadScriptsBeforeUI="true">
</asp:ScriptManager>
In javascript
PageMethods.SendDate(new Date(),function(response){
// success
});
And use <asp:AsyncFileUpload .. for uploading file asyncly
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="xc" %>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<xc:AsyncFileUpload OnClientUploadError="uploadError"
OnClientUploadComplete="uploadComplete" runat="server"
ID="AsyncFileUpload1" Width="400px" UploaderStyle="Modern"
OnUploadedComplete = "FileUploadComplete"
/>
<asp:Label id="lblMsg" runat="server" />
</form>
Also
protected void FileUploadComplete(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs(Server.MapPath("Uploads/") + filename);
}
And js
<script type = "text/javascript">
function uploadComplete(sender) {
$get("<%=lblMsg.ClientID%>").innerHTML = "File Uploaded Successfully";
}
function uploadError(sender) {
$get("<%=lblMsg.ClientID%>").innerHTML = "File upload failed.";
}

Asynchronous output to textbox in asp.net

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 + ",";
}
}

How do I retrieve the value of an HTML textbox in C# using MonoDevelop

I am new to MonoDevelop, C#, and Linux. To learn how things work, I'm trying to make a simple web page to input the height and width of a rectangle, then use a submit button to calculate and display the area.
I have two problems. First, I can't get the submit button to actually do anything. Second, I'm having trouble getting the value of the textboxes in the C# code. Once I get it, I think I can handle the values okay to calculate the area and spit it back out. The Request.Form commands were my point of problem I believe.
Here's what I have so far:
<body>
<div>
Height <input type="text" name="inHeight" value=1 /><br />
Width <input type="text" name="inWidth" value=1 /><br />
<br />
<input type="button" name="btnCalculateArea" value="Calculate Area" onclick="CalculateArea()" /><br />
<br />
<%= Html.Encode(ViewData["Message"]) %>
</div>
</body>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace rectangle_area.Controllers
{
public class HomeController : Controller
{
public string strHeight;
public string strWidth;
public int intHeight;
public int intWidth;
public double dblArea;
public ActionResult Index ()
{
return View ();
}
public ViewResult CalculateArea ()
{
strHeight = Request.Form ["inHeight"];
strWidth = Request.Form ["inWidth"];
if (strHeight != null && strWidth != null) {
intHeight = Convert.ToInt16 (strHeight);
intWidth = Convert.ToInt16 (strWidth);
dblArea = intHeight * intWidth;
ViewData ["Message"] = "The area of this rectangle is " + dblArea + " square units.";
} else {
ViewData ["Message"] = "Please enter values for the Height and Width.";
}
return View ();
}
}
}
You have to bind there a function that makes an ajax call to your controller.
Thanks for the direction, Christos! With the help of a friend and more research, I got it working. Here's what I ended up with:
<head runat="server">
<title>Calculate the area of a rectangle</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/Home/CalculateArea';
$('#calcBtn').click(function(){
$.ajax({
type: "GET",
url: serviceURL,
data: { inHeight: $("#inHeight").val(), inWidth: $("#inWidth").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
<body>
<div>
Height <input type="text" id="inHeight" value=2 /><br />
Width <input type="text" id="inWidth" value=3 /><br />
<br />
<input id="calcBtn" type="submit" value="Calculate Area" /><br />
<br />
</div>
</body>
[HttpGet]
public ActionResult CalculateArea ()
{
strHeight = Request.Params ["inHeight"];
strWidth = Request.Params ["inWidth"];
if (strHeight != null && strWidth != null) {
intHeight = Convert.ToInt16 (strHeight);
intWidth = Convert.ToInt16 (strWidth);
dblArea = intHeight * intWidth;
ViewData ["Message"] = "The area of this rectangle is " + dblArea + " square units.";
} else {
ViewData ["Message"] = "Please enter values between 0 and 999.";
}
return Json(ViewData["Message"], JsonRequestBehavior.AllowGet);
}

How to get javascript values on code behind in c#

I need to get javascript values on code behind in c#.I know i can use hidden field but there is no server control on page for postback.Please tell me how can get vales in code behind.
Here is my code:
<html>
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: 'APPID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
FB.api('/me', function (me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('myJSString').value = me.name;
alert(document.getElementById('myJSString').value);
document.getElementById('Email').innerHTML = me.email;
document.getElementById('profileImg').src = uid;
// document.getElementById('ctl00_CPHDefault_tcTPS_TPProd_ctl01_tcProduction_TPNewT‌​itlesStatus_ChangedRowsIndicesHiddenField').value = uid;
// alert('yyy');
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div id="Result" class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(logout)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />
<form runat="server">
<asp:HiddenField runat="server" id="myJSString" />
</form>
</div>
</div>
</body>
</html>
You can see there is no server control so how i can get NAME,UID variables in code behind.
Thanks
You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.
Html
<asp:hiddenfield id="ValueHiddenField" runat="server"/>
Javascript
document.getElementById('ValueHiddenField').value = "yourValue";
Code behind
string yourValue = ValueHiddenField.Value;
Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: {'yourParam': '123'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Code behind
[WebMethod]
public static void YourMethod(string yourParam)
{
//your code goes here
}
I would investigate the use of ASP.NET AJAX Page Methods, because they allow for script callable stand-alone web services that live in an .aspx page, like this:
Page Method in your code-behind file (call it default.aspx for discussion's sake):
[WebMethod]
public static string SaveData(string name, string uid)
{
// Logic here to do what you want with name and uid values (i.e. save to database, call another service, etc.)
}
jQuery call to default.aspx's SaveData method:
$.ajax({
type: "POST",
url: "default.aspx/SaveData",
data: "{'name':'John', 'uid':'ABC123'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Notes: ASP.NET AJAX Page Methods automatically encode their response to JSON so you will not see any JSON serialization in the code-behind or any serialization logic at all.
For more information about ASP.NET AJAX Page Methods check out Using jQuery to directly call ASP.NET AJAX page methods
You can use following method:
<script language="javascript" type="text/javascript">
function returnString() {
var val = 'sampleValue';
return val;
}
</script>
C# Code to get the return value of the above function:
ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", "<script language="javascript">var a=returnString();alert(a);</script>");
Or simply as Adil said, can use hidden field and assign value:
<asp:HiddenField ID="hField" Value="0" runat="server" />
<asp:Button ID="Button1" runat="server" OnClientClick="returnString();"
Text="Button" onclick="Button1_Click" />
script for assigning value:
<script language="javascript" type="text/javascript">
function returnString() {
debugger;
document.getElementById("hField").value = "sampleValue";
}
</script>

Categories

Resources