Need Help in ajax debugging - c#

<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myButton').click(function () {
$.ajax({
type: "POST",
url: "testajax.aspx/GetHello",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
$('#myLabel').text(data.d);
},
error: function (err) {
console.log(err);
}
});
});
});
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<input id="myButton" type="button" value="Click me" />
<%--<asp:Button ID="myButton" runat="server" Text="Click me" />--%>
<asp:Label ID="myLabel" runat="server" Text="" />
</div>
</form>
</body>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public partial class DataUpdate__testa : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string GetHello()
{
return "Hello";
}
}
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
is set in the web.config
Looking for a long time still don't know what is wrong..
Any help would be greatly appreciated, thanks!
                                      

Your code behind page looks REALLY but REALLY messed up.
Start from scratch. Add a new blank page, say called testajax.aspx.
So, the code inside of the page will be this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
static public string GetHello()
{
return "Hello";
}
DO NOT mess around with anything else in that page. In fact, when you type in the above [WebMethod], vs should automatic add to the using's this:
using System.Web.Services;
But, DOUBLE check that the above "using" exists on this test page.
Now, of course I don't mess with the rest of the code or how the page is created. (and YOU should not have to either!!!!).
So, while I did not type in the rest of the page, a full code behind code listing would be this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CSharpWebApp
{
public partial class testajax : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
static public string GetHello()
{
return "Hello";
}
}
But, of course YOU only typed in the ONE simple web method on that page of our simple routine GetHello.
NOTE VERY careful:
Since this is a not a separate custom "asmx" web service page, then ANY and ALL methods in that page MUST be marked as static. (it is your free choice to add methods to a asmx page, or as I often do, shove them into a existing web page, but for EXISTING aspx pages, you MUST as noted mark the function as static.
Ok, and now your js code. You have a whole bunch of extra trailing ):: etc. The editor should help you, but to be fair, js code can be hard, since it not compiled nor resolved during the build process.
However, our markup can thus look like this:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function myjavatest() {
$.ajax({
type: "POST",
url: "testajax.aspx/GetHello",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (data) {
$('#myLabel').text(data.d);
},
error: function (err) {
console.log(err);
}
});
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="myButton" runat="server" Text="Click me"
OnClientClick="myjavatest();return false" />
<br />
<asp:Label ID="myLabel" runat="server" Text="" ClientIDMode="Static"/>
</div>
</form>
So, above is all you need.
A few things:
As noted, WHEN you going to add web methods to a existing page, then make sure it marked as static.
Next up:
To reference controls on a page with jQuery, then make the label, or text box, or whatever with clientid="Static". (since the asp.net processor will mess with id names, this setting prevents that).

Related

Struggling to ASP.NET C# Ajax novice question

I changed the code with a simple like these
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#RadioButtonYes').click(function () {
var enterdata = document.getElementById("RadioButtonYes").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text1 = "ajaxyes";
alert(text1);
},
failure: function (response) {
alert(response.d);
}
});
});
$('#RadioButtonNo').click(function () {
var enterdata = document.getElementById("RadioButtonNo").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text2 = "ajaxno";
alert(text2);
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<div>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" GroupName="G" />
</div>
.cs side
I tried to add some debugging messages, but it didn't work.
public partial class Radio_Button__radiobutton03ask : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public void SyncData(string data)
{
if (data != "")
{
if (data == "RadioButtonYes")
{
Response.Write("SyncDataYes");
//return RadioButtonYes;
}
else if (data == "RadioButtonNo")
{
Response.Write("SyncDataNo");
//return RadioButtonNo;
}
else
{
Response.Write("SyncDataOther");
}
}
}
}
I am helping the company to debug some old projects(C# webforms), but struggling to simple ajax.
The goal is when pressing the radio button run ajax "ajaxyes" and .cs "SyncDataYes" message normally, but the above code does not respond when pressed.
I have tried alot of fixes i found online but none seem to work well for, if someone could help, it would be greatly appreciated.
first, there is a LOT of issues here.
first up:
[WebMethod]
public void SyncData(string data)
Why are you marking/making the routine as "void". Void of course in c# means that the function will NOT return anything!!!! - That should be a first obvious issue!
And since you using this inside of the web page (as opposed to a separate asmx page? Then you need to set the routine as static - since NO page class instance will have been created here (there is NOT post back).
next up:
Response.Write("SyncDataNo");
WHY would you try and use Response.Write? Response write is ONLY for writing into a web page. But the WHOLE IDEA of ajax is the web page is not and will not be sent up to the server for code behind to operate on. So, response write does not make sense AT ALL here! It can't be used, and you can EVEN see that the compiler does not allow this (now that you fixed and removed the void from that routine).
A so called "ajax" call?
The idea here is that you do NOT have to post back the web page. This is great since you don't get the browser "spinner" and all that waiting time. It also great since it runs VERY fast since you don't and are NOT posting the web page back to the server.
Of course the big downside is then the code behind can't see nor use, nor modify any of the controls on the web page. (since the web page is still sitting on the users desktop). So code behind for a web method can't see nor modify controls on the page (the calling JavaScript and ajax call HAS do to that change of controls).
So, lets use all of the above information, and fix this code.
Lets make a simple C to F temperature converter.
So, first up, that web method is to return a value, so we remove the void.
next up, as I stated, the page class "instance" is NOT re-created when we call such a web method, so that method ALSO MUST be marked as static. (I assume you know what that means, right???).
Ok. So the web method should look like this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static Double ConvertToC(Double MyC)
{
Double CelResult = (MyC * 1.8) + 32;
return CelResult;
}
So, we HAVE to make this routine static. (the page class is not re-reated, and the web page is STILL sitting on the users desktop).
So, say our markup looks like this:
<div style="text-align:right;width:20%">
<label style="font-size:large">Enter Celsious Tempature</label>
<asp:TextBox ID="txtC" runat="server" style="font-size:large;margin-left:5px;text-align:center"
TextMode="Number" Width="80px" Wrap="False"
ClientIDMode="Static">
</asp:TextBox>
<br /> <br />
<div style="text-align:center">
<asp:Button ID="cmdConvert" runat="server" Text="Convert to °F" CssClass="btn"
OnClientClick="MyConvert();return false"/>
</div>
<br />
<label style="font-size:large">Fahrenheit</label>
<asp:TextBox ID="txtF" runat="server" style="font-size:large;margin-left:5px;text-align:center"
Width="80px" Wrap="false"
ClientIDMode="Static">
</asp:TextBox>
</div>
<script>
function MyConvert() {
var txtC = $("#txtC");
var txtF = $("#txtF");
$.ajax({
type: "POST",
url: "Autocom.aspx/ConvertToC",
data: JSON.stringify({ MyC: txtC.val()}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (MyReturn) {
txtF.val(MyReturn.d);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
I'm also a bit lazy, so I used clientID mode = static, as that makes the jQuery selector nice and easy to type in.
So, when we run the above, we get this result:
so, now your "mess".
it not particular what you goal here is with your sample.
(going for coffee, but study, and try the above).
Edit: Try this sample code
Your c# method in the page:
[WebMethod]
public static string SyncData(string data)
{
string sResult = "";
if (data != "")
{
if (data == "Yes")
{
sResult = "SyncDataYes";
}
else if (data == "No")
{
sResult = "SyncDataNo";
}
else
{
sResult = "SyncDataOther";
}
}
return sResult;
}
And your markup is this:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server"
Checked="true" GroupName="G"
onclick="MyBtnClick('Yes')"
ClientIDMode="Static"
/>
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server"
GroupName="G"
onclick="MyBtnClick('No')"
ClientIDMode="Static"
/>
<br />
<h3>Result</h3>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<script>
function MyBtnClick(sYesNo) {
$.ajax({
type: "POST",
url: "TestAjax.aspx/SyncData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({data : sYesNo }),
success: function (MyResult) {
$('#TextBox1').val(MyResult.d);
},
failure: function (MyResult) {
alert('error');
}
});
}
</script>
Since ASP run at server control's ID will be generated different ID in client side, so these 2 event handlers binding will not work.
$('#RadioButtonYes').click(function () {...}
$('#RadioButtonNo').click(function () {...}
You could try 2 solutions:
Using control's ClientID for event binding
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
Adding ClientIDMode="Static" attribute to ASP control
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" ClientIDMode="Static" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" ClientIDMode="Static" GroupName="G" />
** UPDATE:**
Your code also has two more problems:
1 - DataType of your ajax request (json) does not match with response type from server code (text/plain). You could check demo of not matching dataType of ajax request here: https://jsfiddle.net/p2yzLqu1/3/
2 - You were using wrong ajax's callback function failure. We should use done (success) and fail (error) callback functions instead. Please check sample of using done and fail callback at above demo.

How to provide a generic url to jQuery ajax call from different directory of an ASP.NET application [duplicate]

This question already has an answer here:
How to refer http handler file from jQuery ajax under different directory of asp.net web application
(1 answer)
Closed 5 years ago.
I created a http handler file in following directory of my application
I am referring this handler from common.js file using jQuery ajax and common.js file referred in aspx pages StoresSummary.aspx & EmoloyeeProfile.aspx
From EmoloyeeProfile.aspx I am able to call the handler and getting the output, but from StoresSummary.aspx jquery ajax call getting failed.
I know the cause of failure because the path of CommonHandler.ashx file does not map correctly due to location hierarchy of StoresSummary.aspx.
This is a sample code I am posting, the http handler file I need to call from jQuery ajax and aspx pages may exists in different directory of same web application.
How do I give path of CommonHandler.ashx in ajax jQuery call so any location hierarchy of my aspx page can call it.
This is my code
common.js
function GetMessage(key) {
var message = '';
$.ajax({
type: 'POST',
url: '../../Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});
function onSucess(res) {
message = res;
}
function OnFailed(res) {
alert('failed');
}
return message;
}
CommonHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace DemoWebApp.Common.Handlers
{
/// <summary>
/// Summary description for CommonHandler
/// </summary>
public class CommonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(GetData(context.Request["MessageKey"]));
context.Response.ContentType = "text/html";
context.Response.Write(result);
}
private string GetData(string Id)
{
return DateTime.Now.ToString(); //just to demostrate
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
StoresSummary.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../../../Common/Scripts/common.js"></script>
<script src="../../../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
EmoloyeeProfile.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Common/Scripts/common.js"></script>
<script src="../Common/Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Get Message" OnClientClick="return CallMethod();" />
</div>
</form>
<script type="text/javascript">
function CallMethod() {
var msg = GetMessage('001');
alert(msg);
return false;
}
</script>
</body>
</html>
Provide absolute path to the handler. You are providing relative path now. See the ajax url section.
$.ajax({
type: 'POST',
url: '/Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'MessageKey': key },
success: onSucess,
error: OnFailed,
async: false
});

Getting and setting ASP.NET attributes in jquery

I am adding a new attribute to a DataList control in asp.net. I want to set the attribute on the server in C#. I then want to modify it in jQuery on the client, and get the new value of the attribute in C# back on the server. I think if I initialize the attribute to say "0" in my .aspx code, it get reset to "0" during the postback.
So, I'm using DataList.Attributes.Add() to create and init the attribute value during my render. On the client, I use .attr in jQuery to modify the value. During the postback on the server, I use DataList.Attributes["attributeName"] to get the new value, but it's null. I've changed EnableViewState for the DataList, its parent, and grandparent to true and false, but I still get a null value.
Is there a way to create and init an attribute on the server, modify it in jQuery on the client, and get the new value in C# back on the server?
A server control's attributes are persisted in the page viewstate. On postback the server control is re-created, and, its attribute values are re-created by parsing the viewstate value, from the posted data.
Hence any attempt to modify a server-created-control-attribute, or, add an attribute on a server-control from the client will not work. (More precisely it won't be very straight forward even if it might be possible).
Anyhow, a browser is "programmed" to send (over the wire) data held inside any html input or select control (hope I didn't miss anything) nested inside the html form. Further, all such controls need to be identified by the value specified by the name attribute. For e.g.
<form method="post" action="default.aspx">
<input type="text" name="foo" value="123"/>
<input type="submit" value="submit to server"/>
</form>
If one such form is submitted to a server like ASP.NET (which is an abstraction of IIS which implements the CGI standard), you can get the value of the textbox by doing something like:
string fooValue = Request.Form["foo"];
A browser program is usually programmed to send data corresponding the name and value attributes only.
Now, since you are looking at getting more than one kind of data on the server, but still associated with a single control, your options are to go with any of the following:
Access the value from two separate controls on the server. However, its your job to figure their are associations.
You can think of a user control approach, which ultimately is like the above but if written will give you a neat encapsulation.
Here is a small example of the 2nd approach:
CompositeControl.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CompositeControl.ascx.cs" Inherits="WebApp.Attributes.CompositeControl" %>
<label>Enter Name</label>
<asp:TextBox runat="server" ID="tbxName"></asp:TextBox>
<asp:HiddenField ID="hdnAge" runat="server" />
CompositeControl.ascx.cs:
using System;
namespace WebApp.Attributes
{
public partial class CompositeControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!string.IsNullOrEmpty(this.HiddenFieldClientId))
{
hdnAge.ClientIDMode = System.Web.UI.ClientIDMode.Static;
hdnAge.ID = this.HiddenFieldClientId;
}
}
public string Name
{
get
{
return tbxName.Text;
}
set
{
tbxName.Text = value;
}
}
public int Age
{
get
{
return int.Parse(hdnAge.Value);
}
set
{
hdnAge.Value = value.ToString();
}
}
public string HiddenFieldClientId { get; set; }
}
}
default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebApp.Attributes._default" %>
<%# Register src="CompositeControl.ascx" tagname="CompositeControl" tagprefix="uc1" %>
<!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 src="Scripts/jquery-2.1.0.min.js"></script>
<script>
$(function () {
$('#tbxAge').val($('#personAge').val());
$('#btnSetAge').click(function () {
$('#personAge').val($('#tbxAge').val());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:CompositeControl ID="CompositeControl1" runat="server" HiddenFieldClientId="personAge" />
<br />
<input id="tbxAge" type="text" />
<input id="btnSetAge" type="button" value="Set" />
<p>Hit <strong>set</strong> before clicking on submit to reflect age</p>
<asp:Button runat="server" ID="btnSubmit" Text="Submit"
onclick="btnSubmit_Click" />
<br />
<asp:Literal runat="server" ID="ltrlResult"></asp:Literal>
</div>
</form>
</body>
</html>
default.aspx.cs:
using System;
namespace WebApp.Attributes
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CompositeControl1.Age = 23;
CompositeControl1.Name = "Default";
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
ltrlResult.Text = string.Format("<p>{0}</p><p>{1}</p>", CompositeControl1.Name, CompositeControl1.Age);
}
}
}
You could make an AJAX call in wich you send the changes made it with jquery to some webservices method in your code behind to handle it.
AJAX jquery post change call:
$.ajax({
type: 'POST',
url: 'Default.aspx/Checksomething',
data: '{"userValuePostChanged ": "' + DtLValue+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
webservices C#
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Checksomething(string userValuePostChanged)
{
//Do some stuff with userValuePostChanged
return "something else"
}
This are the links where I took the examples:
consume .net web service using jquery
How to use jQuery to make a call to c# webservice to get return value
http://www.codeproject.com/Articles/66432/Consuming-Webservice-using-JQuery-ASP-NET-Applicat

How to call code behind server method from a client side JavaScript function?

I am having an JavaScript function for a HTML button click event in ASPX page. And a server Method in its code behind page. Now I want to call the server method from the JavaScript function with some parameters only when the HTML button is clicked by the user.
Please don't change this scenario and also don't use any asp.net contols in the aspx page while replying. Because only HTML controls are allowed. Can anyone help me on this?
Here is the code,
Code in markup:
<script language="javascript" type="text/javascript">
function btnAccept_onclick() {
var name;
name = document.getElementById('txtName').value;
// Call Server side method SetName() by passing this parameter 'name'
</script>
<input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />
Code-behind:
public void SetName(string name)
{
// Code for some functionality
}
Yes, you can make a web method like..
[WebMethod]
public static String SetName(string name)
{
return "Your String"
}
And then call it in JavaScript like,
PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);
This is also required :
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
In my projects, we usually call server side method like this:
in JavaScript:
document.getElementById("UploadButton").click();
Server side control:
<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />
C#:
protected void Upload_Click(object sender, EventArgs e)
{
}
If you dont want to use ajax than
Code behind
void myBtn_Click(Object sender,EventArgs e)
{
//SetName(name); your code
}
.aspx file
<script language="javascript" type="text/javascript">
function btnAccept_onclick() {
var name;
name = document.getElementById('txtName').value;
document.getElementById('callserver').click();
// Call Server side method SetName() by passing this parameter 'name'
</script>
<div style="dispaly:none;">
<input type="button" id="callserver" value="Accept" click="myBtn_Click" runat="server" />
</div>
<input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />
or use page method
.cs file
[ScriptMethod, WebMethod]
public static string docall()
{
return "Hello";
}
.aspx file
<script type="text/javascript">
function btnAccept_onclic() {
PageMethods.docall(onSuccess, onFailure);
}
function onSuccess(result) {
alert(result);
}
function onFailure(error) {
alert(error);
}
</script>
check this : http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx
JS Code:
<script type="text/javascript">
function ShowCurrentTime(name) {
PageMethods.GetCurrentTime(name, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>
HTML Code:
<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />
Code Behind C#
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
I had to register my buttonid as a postbacktrigger...
RegisterPostbackTrigger(idOfButton)
Ajax is the way to go. The easiest (and probably the best) approach is jQuery ajax()
You'll end up writing something like this:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// do something when done
}
});
Try creating a new service and calling it. The processing can be done there, and returned back.
http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e
function makeCall(operation){
var n1 = document.getElementById("num1").value;
var n2 = document.getElementById("num2").value;
if(n1 && n2){
// Instantiate a service proxy
var proxy = new Service();
// Call correct operation on vf cproxy
switch(operation){
case "gridOne":
proxy.Calculate(AjaxService.Operation.getWeather, n1, n2,
onSuccess, onFail, null);
****HTML CODE****
<p>Major City: <input type="text" id="num1" onclick="return num1_onclick()"
/></p>
<p>Country: <input type="text" id="num2" onclick="return num2_onclick()"
/></p>
<input id="btnDivide" type="button" onclick="return makeCall('gridOne');"
In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:
aspx code:
<asp:Button runat="server" id="btnResponse1" Text=""
style="display: none; width:100%; height:100%"
OnClick="btnResponses_Clicked" />
<div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>
C# code behind:
protected void btnResponses_Clicked(object sender, EventArgs e)
{
if(sender == btnResponse1)
{
//Your code behind logic for that button goes here
}
}
// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
**pagename/methodname** *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
function(result)
{
}
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
{
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json",
success: function(result)
{
if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
{
CallBackFunction(result);
}
},
error: function(result)
{
alert('error occured');
alert(result.responseText);
window.location.href="FrmError.aspx?Exception="+result.responseText;
},
async: true
});
}
//page name is Default.aspx & FunPubGetTasks method
///your code behind function
[System.Web.Services.WebMethod()]
public static object FunPubGetTasks(string a, string b)
{
//return Ienumerable or array
}

I have a btnSave button i want to call this btnSave_Click method on click of an input button btnmore through jquery how can i do that

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Jquery</title>
<script type="text/javascript" src="scripts/jquery-1.4.2.js"></script>
<script type="text/javascript"> jQuery(document).ready(function () {
$('#btnmore').click(function () {
$('<%=btnSave.ClientID%>').click();
alert('done');
$.ajax({type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{}',
dataType: 'json',
url: 'Default.aspx/btnSave_Click',
success: function(result){
alert(result);} });
});
});</Script>
</head>
<body>
<form id="form1" runat="server">
<asp:scriptManager id="script1"></asp:scriptManager>
<div>
<table>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<input type="button" id="btnmore" value="More" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Server side code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string MyMethod()
{
return "abc";
}
[WebMethod]
protected void btnSave_Click(object sender, EventArgs e)
{
Response.Write("abc");
}
}
Why not just use:
$('#btnmore').click(function(
$('#btnSave').click();
});
Note that you will need to get the actual name of btnSave, because it will probably be in a naming container. Something like this should get the correct id:
$('<%=btnSave.ClientID%>').click();
This can be an alternate solution. On the same button you can call 2 click functions; one client side and another server side.
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Click" OnClientClick=" return buttonClientValue()" />
buttonClientValue() function should return true or false. If returns true than only btnSave_Click will be executed, otherwise not.
Here's what I like to do. Since you can't really control the ID assigned by ASP.NET, you need some javascript code in the same page as the button you want clicked. you can wrap that code in a function with a known name that you can call from external .js files if need be. But you need to let ASP.NET generate the 'click' function for you:
function clickit() {
<%=this.Page.GetPostBackClientEvent(this.btnSave, string.Empty)%>;
}
then elsewhere in your javascript just call clickit()
$('#btnmore').click(function(
$('#btnSave').click();
});
Its work for me.
<script type="text/javascript">
$(document).ready(function () {
$('#_btnSave').click(function () {
$("form").submit();
});
});
</script>

Categories