Call a method in an aspx page - asp.net

Can I call a method which is in an asp.net web page (in aspx.cs page) without checking it in the pageload?
for example '../test2.aspx/TestMethod
In this link I have noticed that we can give url: "PageName.aspx/MethodName", in jquery ajax method. I have tried it and never works for me.

Page Methods is a new mechanism in ASP.Net application where the server code cab be bound to Asp.Net pages
To enable Page methods we need to drag a ScriptManager control to the page and mark
the EnablePageMethods to “True”.
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePageMethods="True">
</asp:ScriptManager>
Go the Code behind file of the page and add a static method
[WebMethod]
public static string HelloWorld(string name)
{
return string.Format("Hi {0}",name);
}
In javascript function we can use PageMethods object to call the WebMethod of the page.
<script type="text/javascript">
function GreetingsFromServer() {
var name = 'Jalpesh';
PageMethods.HelloWorld(name,OnSuccess, OnError);
return false;
}
function OnSuccess(response) {
alert(response);
}
function OnError(error) {
alert(error);
}
</script>

you can use ajax call for another page webmethod
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});

Related

How to update <%=Convert.ToString() %> using update panel in asp.net C#

I want to update the test variable through ajax & C# backend code. I have set test variable as string builder in .cs file & want to update the value of the same variable through .cs code using ajax while clicking on div tag.
Code in .aspx:
<asp:UpdatePanel ID="upre" runat="server">
<ContentTemplate>
<%=Convert.ToString(test) %>
</ContentTemplate>
</asp:UpdatePanel>
Ajax code:
$(".mb-2").click(function (e) {
$.ajax({
type: "POST",
url: "one.aspx/Subscribe",
contentType: "application/json; charset=utf-8",
data: '{"name":"test","email":"test#gmail.com"}',
dataType: "json",
success: function (msg) {
if (msg.d) {
alert(msg.d);
}
},
error: function (req, status, error) {
alert("Error try again");
}
});
return false;
});
Backend Code:
[WebMethod]
public static string Subscribe(string name, string email)
{
AllApps abc = new AllApps();
abc.iPriceFrom = 50;
abc.iPriceTo = 100;
abc.test();`enter code here`
return "thanks " + name + ", your email " + email + " is subscribed to our newsletter.";
}
I tried with the above code but it is not updating the variable value at the front side. Data is updating from backend (.cs) file. I want to update the test variable through ajax & C# backend code. I have set test variable as string builder in .cs file & want to update the value of the same variable through .cs code using ajax while clicking on div tag.

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.

Call a function in code behind without using javascript

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

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.

Viewdata not showing in partial view

Hi guys i have controller which returns a partial view, the controller is called by ajax script. The partical view has no problem showing viewdata first time, But when ajax script is invoked second time the partical view does not update it self with new viewdata.
code for controller
[HttpGet]
public ActionResult getPart(int id)
{
ViewData["partical"] = id;
return PartialView("test");
}
code for partial view
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PovertyBayHotel.Models.testmodel>" %>
<p>just a test</p>
<%: ViewData["partical"]%>
and the ajax which call the controller
<script type="text/javascript">
$(document).ready(function () {
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
});
});
</script>
Might be a caching issue. Try HTTP POST instead of GET or set the ifModified and cache options to false as below:
$("#DropDown").change(function () {
var course = $("#DropDown > option:selected").attr("value");
$.ajax({
type: 'GET',
ifModified: false,
cache: false,
url: '/Reservation/getPart',
data: { id: course },
success: function (data) {
$('#ExtraBox').replaceWith(data);
}
});
Also, try to debug your code and see really what is going on.
Edit:
The problem has been solved by changing $('#ExtraBox').replaceWith(data); with $('#ExtraBox').html(data);.

Resources