using ajax in asp.net c# - c#

how can i use ajax to call a server side method i tried this code but it gives me the alert error messsage and i can't find my problem please help and thank you :
enter code here
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ImageEditor_UserControl.ascx.cs" Inherits="ImageEditor_UserControl" %>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=uploadButton.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: "ImageEditor_UserControl.ascx/helo",
data: "{}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function () { alert("success"); },
error: function () { alert("error"); }
})
return false;
});
});
</script>
<asp:Button ID="uploadButton" runat="server" Text="Upload" />
C# Code
[WebMethod]
public static string helo() {
return "Message from server.";
}

You should call *.asmx files (there are other options but this is for the beginning).
Look out for tutorials on web services & ajax consuming.

Have you checked on the line $('#<%=uploadButton.ClientID %>').click(function () { that the
<%=uploadButton.ClientID %> is actually replace by the value and not taken literally?

Do you use firefox? if yes, install the addon "FireBug". Enable firebug to check the request and the response.
Firebug will show you sometimes the error message returned from the server, as in you jquery syntax you are not loading the attributes for the method anonymous method callback for error.
error: function (req,error) { alert("error: " + req.statusText); }
This will give you a heads up on what is going wrong.

Unfortunately you cannot call a page method (server side method) that is a part of a user control. You will have to use a method in an aspx page.

Related

Ajax Jquery POST method not working in ASP.NET after changing Jquery version to jquery-3.6.3

I'm changing Jquery version from jquery-1.10.2 to jquery-3.6.3 but the method callings are not working due to this version change. My .NET Framework version is 4.7.2
I have used the new reference like below:
<script src="../Scripts/Version3.6.3/jquery-3.6.3.min.js?version=<%=ApplicationVersion.GetApplicationVersion()%>" type="text/javascript"></script>
calling client side JQuery POST method:
$.post("/employer/employerbrowse.aspx/SelectEmployer",
{ key: key },
function (data, textStatus, jqXHR) {
alert(data);
});
c# method:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false)]
public string SelectEmployer(string key)
{
string strUrl = "";
return strUrl;
}
After calling the "SelectEmployer" method it redirecting to page load only not in the desired page method.
Thanks in advance.
use AJAX to make the call to webMethod
$.ajax(
{
type: "POST",
url: "employerbrowse.asmx/SelectEmployer",
data: JSON.stringify({ key: _key}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
}
}
);
Further ... I notice your webmethod is in a normal aspx page, whenever ive tried that it hasnt worked and needed to add a Web Service (asmx) but you might be alright... Youd keep js/ajax call in aspx page if using this.

Is It possible to use web method in C# class?

I'm using web method in C# class file(i.e not a partial class of any web form) and I have html file. I just want to call web method from html file using JQuery AJAX GET and POST methods. Is it possible to do this? Is this have any sense? or i must want use asp web form?
To answer your question it's important that you first understand the prurpose of having a web service.Web services allow us to expose any piece of software over the internet and allow clients to consume it.
In .NET ASMX web services we expose software to the outside world by decorating methods with the [WebMethod] attribute.But even if we apply the [WebMethod] attribute our method will not be available over the internet unless it's inisde a:
.asmx web service file
.aspx web page
Hopefully now you understand why you can't simply define a [WebMethod] inside a standard C# class.Below is a simple example of calling an ASMX web service from a plain html page:
MyService.asmx:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string GreetUser(string name)
{
return String.Format("Hello {0}",name);
}
}
Index.html:
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCallService").click(function () {
$.ajax({
type: "POST",
url: "MyService.asmx/GreetUser",
contentType: "application/json;charset=utf-8",
data: '{name:"' + $("#txtName").val() + '"}',
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<input type="text" id="txtName" />
<input type="button" value="Call Service" id="btnCallService" />
</body>
</html>
Yes you can. Your html file can include a tag with functions that make ajax calls.
Here is a simple example from W3School's site:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
You see that the button has an 'onClick' event, which calls the loadDoc function.
And this is the function:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Here is the link to the tutorial's page:
http://www.w3schools.com/ajax/
Your Ajax Call on HTML will look very similar to this
var options = {
type: "POST",
url: '<%=ResolveUrl("~/FileLocationWhereWebMethodIsDefined") %>',
data: "{'Add Parameters if your web method needs it'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
//jQuery(".overlay").show();
//jQuery(".progress").show();
},
success: function (msg) {
},
error: function (jqXHR, textStatus, errorThrown) {
// jQuery(".overlay").hide();
// jQuery(".progress").hide();
throw Error; // "error";
}
};
jQuery.ajax(options);

Call WebMethod from another project using Jquery

I created a project in Visual Studio named 'MyProject', and Added .aspx file to it named 'MyPage.aspx'.
In 'MyPage.aspx.cs', there is a web method as shown below
[WebMethod(EnableSession=true)]
public static string GetDetails()
{
try
{
var data= HttpContext.Current.Session["mySession"] as myDto;
return myDto.Username;
}
catch
{
return "Sorry";
}
}
Now, I created another project in that same solution named 'NewProject'.
And I have a page in this project as 'NewPage.aspx', from which I am trying to call GetDetails() from 'MyPage.aspx' (MyProject).
So I tried the following code.
NewPage.aspx
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://localhost:2463/MyPage.aspx/GetDetails',
success: function (data) {
alert(data);
},
error: function (response) {
alert('Error');
}
})
});
</script>
but the Web Method isn't getting hit & I get the 'Error' alert displayed.
I also tried this
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:2463/MyPage.aspx/GetDetails",
contentType: "application/json; charset=utf-8",
data: '{}',
datatype: "json",
success: function (msg) {
alert('success');
},
error: function (response) {
alert('Error');
}
});
});
</script>
but no luck.
Plz Help...!!
Sounds like a CORS problem.
By default you cant access a service that is not within the origin domain (scheme, hostname, port).
You have to make sure that link http://localhost:2463/MyPage.aspx/GetDetails is available while making jquery ajax call. For that
you can run MyProject in a seperate instance of VS and then run NewProject in another instance of VS.
Check console in inspect element and find a solution for given error.
You can call webMethod of another page. Your code seems correct.
And no need to write whole URL ('http://localhost:2463/MyPage.aspx/GetDetails') of a page, Just write 'MyPage.aspx/GetDetails'.

Search data in table using ajax in ASP.net MVC

I want to display data in a table based on the search criteria in a textbox. I have implemented it without using Ajax but do not know how to call controller method using jquery and update table data. Please try to solve my problem. Thanks...
Index.cshtml
#model IEnumerable<MvcApplication4.Models.tbl_product>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<title>Index</title>
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function () {
alert("button clicked");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: "{'searchString':'" + document.getElementById('searchString').value + "'}",
async: false,
Success: function (response) {
alert("Success");
window.location.reload();
},
error: function () { alert("error"); }
});
});
});
</script>
</head>
<body>
#* #using (#Html.BeginForm("Index", "Home"))
{*#
#Html.TextBox("searchString");
<input type="button" value="filter" id="Button1" />
#* }*#
<table id="showData">
#{Html.RenderPartial("SearchList");}
</table>
</body>
</html>
SearchList.cshtml(Partial View)
#foreach (var item in Model)
{
<tr>
<td>#item.ProductName</td>
<td>#item.ProductId</td>
<td>#item.ProductDesc</td>
</tr>
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
ProductEntities dbentity = new ProductEntities();
public ActionResult Index()
{
return View(dbentity.tbl_product.ToList());
}
[HttpPost]
public ActionResult Index(string searchString)
{
var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString));
return View(query.ToList());
}
}
$.ajax({
url: '/ControllerName/ActionName',
type: "POST",
data: {criteria: 'criteria'},
contentType: "application/json",
success: function (data) {
//Replace existing table with the new view (with the table).
}
});
//write ControllerName without the key controller.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: JSON.stringify({'searchString':document.getElementById('searchString').value }),
async: false,
Success: function (response) {
alert("Success");
//append the data in between table tbody like,
$('table tbody').html(response);
//No window.location.reload(); It will cause page reload initial data will appear in grid.
},
error: function () { alert("error"); }
});
return false
Hope this helps.
Your ajax request should look like:
$.ajax({
url: '/<ControllerName>/<MethodName>',
type: "POST",
data: requestData,
contentType: "application/json;charset=utf-8",
success: function (data, textStatus, XMLHTTPRequest) {
//Success callback handling
},
error: function (XMLHTTPRequest, textStatus, errorThrown) {
//Error callback handling
},
cache: false //whether you want to cache the response or not.
});
I'm not going to give you the exact answer, but to help you to get it.
There are two steps:
First you must get sure the request is being done, and the response is being get on the browser.
To do so, you can
do it on your way: leave only the alert("Success"); and check it's being run.
better than that, open the browser's developer console (I prefer Chrome, but you can also use IE or FireFox + FireBug add-on) using F12. Set breakpoints and inspect variable values and code flow. See thit tutorial for Chrome developer tools.
set a breakpoint on the server action, and check it's executed
Second Once you're sure the firs part is working fine, use your succes function to replace the table content with the data received in the response. You can do it in several ways with jQuery. For example
$('#showData').html(response);
Again, you can execute this code and inspect the contents of response from the developer's console in your browser. This makes things eaiser when you're starting to use javascript.
(If your action generated the whole table, you could use jQuery's replaceWith which replaces the target, instead of its content. Don't use this for this case).
FINAL NOTE: please, remove this code window.location.reload();!!! This reloads the whole page with the current URL, so whatever thing you do in advance will be lost.

Calling ServerSide Method using Jquery in .Net1.1

I am using .net1.1 and trying to call a server side method using Jquery on click of browser Close button.My code is not working.I am posting my code below.Will anybody Guide me where did i go wrong?
<body MS_POSITIONING="GridLayout" onbeforeunload="javascript:return test()" >
Ceci est une page cachée. Elle est utilisée pour la gestion du multi-fenétrage.
</body>
function test()
{
debugger;
$(document).ready(function() {
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("success");
},
error: function(msg) {
alert("Error! Try again...");
}
});
return false;
})
}
In Code behind
==================
[WebMethod()]
public DateTime GetServerTime()
{
return DateTime.Now;
}
}
The control does not go to this web method,I am not able to debug,COntrol goes to ' $(document).ready(function() ' after that whole block runs.It is not showing any type of error,but alerts are not showing.If I use any other return type instead of DateTime,It is still not working
**When I am Calling this method test on onload,It is showing alert of error Conditon.But I have to call it when broswer is closed.In any Case it is not going to web method.
$(document).ready(function() { ... }) doesn't execute a function but registers a functoin to be executed when the document is loaded.
$(document).ready(function() { ... }) register a function for the load event of the document. You register this function in onbeforeunload event, this function will never be executed. Because when you register the function in onbeforeunload event, the document has already been loaded and is being unloaded.
If you want to call a method in onbeforeunload , just write the JS code to call WebMethod without $(document).ready
function test()
{
// $(document).ready(function() { //delete this
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) { alert("success"); },
error: function(msg) { alert("Error! Try again..."); }
});
return false;
}
Unfortunately, you cannot specifically check for a browser close. Using onbeforeunload will fire when someone is redirected from this page also. Try binding your event using jQuery on DOM load.
$(document).ready(function() {
$(window).unload(function(e) {
e.preventDefault();
test();
});
});
I can't say exactly why your code doesn't because you haven't provided any error information.
Calling web method from script
You need to take a look at your web service, you need to tell it you'll be calling it from script and as the other guy rightly says, you cannot implicitly serialize a DateTime so the laziest way to get this is to just return a string instead.
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string GetServerTime()
{
return DateTime.Now.ToString();
}

Categories