Call a function in code behind without using javascript - asp.net

i am calling a function on onclick, onmousemove and onkeypress event in form tag and the function is in code behind but the method is not executing when user clicking, pressing a key and moving mouse on form1. The code is :
<form id="form1" runat="server" onclick="idletime()" onkeypress="idletime()" onmousemove="idletime()">
.cs file :
protected void idletime(object sender, EventArgs e)
{
Response.Write("hello.");
}

You can use ajax to do that. I am writing down some rough sample code. Hope it may help.
<form id="form1" runat="server" onclick="idletime()" onkeypress="idletime()" onmousemove="idletime()">
<script>
function idletime() {
$.ajax({
type: "POST",
url: "demo.aspx/functionName1",
data: "{parameter1:'" + param1 "',parameter2:'" + param2 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
}
</script>
c# code
using System.Web.Services; --- use this class
[WebMethod]
public static string functionName1(string parameter1, string parameter2)
{
------------------------------;
return "Demo";
}

Related

How can I call a public function from a public shared function in asp.net?

I have this code:
Default.aspx(javascript:)
<script type="text/javascript">
function ShowChartSpider(group_id) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/MethodToCreateChart",
dataType: "json",
data: "{'parameter1':" + JSON.stringify(group_id) + "}",
success: function (data) {
alert("all correct");
console.log(data);
},
error: function (data) {
alert(data);
console.log(data);
}
}
);
}
</script>
Default.aspx.vb
<WebMethod()>
Public Shared Function MethodToCreateChart(parameter1 As String)
WebChartControl1.Series("sectorbuys").Points.Add(New SeriesPoint("value1", "156"))
WebChartControl1.DataBind()
End If
Return ""
End Function
The code in view aspx from the chart is:
<dxchartsui:WebChartControl ID="WebChartControl1" runat="server">
// some code
</dxchartsui:WebChartControl>
So in MethodToCreateChart I can't call my WebChartControl1, but if remove shared I can call the WebChartControl1 control, but the ajax method stops working, so how can I call a control in my aspx keeping my
Public Shared Function MethodToCreateChart?
PageMethod/WebMethod can access the session state but can't access the controls on the page, we can transfer the related property of control as a parameter that you want to get on WebMethod when you call WebMethod on the client.

Error in Focus on textbox using asp.net web appln

In the below code i have a textbox when focus comes to my textbox it should call serverside codebehind file using ajax but in my case i can get success alert but it is not moving to serverside and return the value pls help me to fix the issue.
code:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg); //awesome, it works!
},
error: function (xhr) {
}
});
});
});
</script>
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" ClientIDMode="Static" OnTextChanged="txtField_TextChanged"></asp:TextBox>
codebehind
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
return "awesome, it works!";
}
You function should look like the following
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
return "awesome, it works!";
}
Here is a sample link
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Add ASP.NET Image from Page Method

I am making an Ajax request with data to a Page Method in my code behind in my ASP.NET Web Forms application. I have a Panel control in my aspx page but I cannot get the control from that Page Method with its ID. I can get it from the Page_Load event though. What can I do to get the Panel control from the page method or is it not possible or maybe an alternative?
<asp:Panel ID="pnlImages" runat="server"></asp:Panel>
<script type="text/javascript">
function GetProductId() {
$.ajax({
type: "POST",
url: "Default.aspx/GenerateQrCode",
data: "{'Products':" + JSON.stringify(data) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
},
success: function (msg) {
alert('Success');
}
});
}
</script>
[WebMethod]
public static void GenerateQrCode(List<Product> Products)
{
foreach(var product in Products)
{
string qrCodeLocation = products.Where(pid=>pid.ProductId == product.ProductId).Select(s=>s.QrCode).FirstOrDefault().ToString();
Image image = new Image();
image.ID = product.ProductId.ToString();
image.ImageUrl = qrCodeLocation;
//Cannot get 'pnlImages' here
}
}
You won't be able to do that, WebMethod doesn't follow the same flow as normal page methods. It's not even a instance method but static.
You'll have to return the information on client and create the image there using javascript.

How to post and access the data using jquery ajax in asp.net webforms?

Here is my current code:
Here is for default.aspx
<body>
<form id="form1" runat="server">
<div id="mydiv">
</div>
</form>
<script>
$(document).ready(function () {
$.ajax({
url: 'Default2.aspx',
data: "{ 'name': '" + "randel" + "' }",
type: "POST",
success: function () {
// alert('insert was performed.');
$("#mydiv").empty();
$("#mydiv").load("Default2.aspx #div");
},
error: function (data, status, jqXHR) { alert(jqXHR); }
});
})
</script>
</body>
Then for Default2.aspx, I want to access the data like this:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Request.Form["name"].ToString();
}
This looks like you want to use WebMethod in ASP.NET:
$(document).ready(function () {
$.ajax({
url: 'Default2.aspx/HelloWorld',
data: "{ 'name': '" + "randel" + "' }",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert('insert was performed.');
$("#mydiv").empty();
$("#mydiv").html(data);
},
error: function (data, status, jqXHR) { alert(jqXHR); }
});
});
and in your code behind you should do this:
[WebMethod()]
public static string HelloWorld(string name)
{
string message = "Hello " + name;
return message;
}
WebMethods are in some kind better than doing __doPostBack() because you controll all client-server traffic using for example jQuery.
More about WebMethods: here or just google WebMethods ASP.NET.
And If you want to receive some form value you should put it on $.ajax data parameter and add the same parameter in WebMethod.
EDITED
From the code you post I see that you want send from Default.aspx some data to Default2.aspx and load some content from Default2.aspx (#div).
You can do this:
$.ajax({
url: "/Default2.aspx",
type: "GET",
dataType: "html",
async: false,
data: { "name": "randel"
},
success: function (obj) {
// obj will contain the complete contents of the page requested
// use jquery to extract just the html inside the body tag
$content = $(obj).find('body #div').html();
// then update the dialog contents with this and show it
}
});
And in code behind:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Request.QueryString["name"];
}

Jquery ajax postback not hitting server method?

This is some of the code on the aspx page with the ajax post:
<div>
Make Comment: <br />
<textarea rows="7" cols="20" id="comment_content"></textarea><br />
<input type="button" id="Make_Comment" value="Make Comment" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Make_Comment").click(function () {
$.ajax({
type: "POST",
url: "Conversation.aspx/AddComment",
data: '{ comment: This is a test comment via ajax postback }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Got Back to code");
}
});
});
});
</script>
And here is the method I am trying to hit on the server side:
[WebMethod]
public static void AddComment(string data)
{
}
I have placed a breakpoint by the server side method but its not hitting it, what could be the issue?
Couple of things :
your data ina ajax call
data: '{ comment: This is a test comment via ajax postback }'
should be
data: "{'comment':'This is a test comment via ajax postback'}",
And your WebMethod :
AddComment(string data)
Should be
AddComment(string comment)
Try this:
<script type="text/javascript">
$(document).ready(function () {
$("#Make_Comment").click(function () {
var comment = $("#comment_content").val();
var Params = { comment : comment };
$.ajax({
type: "POST",
url: "Conversation.aspx/AddComment",
data: Params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Got Back to code");
}
});
});
});
</script>
In your controller set the httppost.
[WebMethod]
[HttpPost]
public static void AddComment(string comment)
{
}

Resources