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

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);

Related

Convert string to HTML to inject to paragraph via WebMethod

Im doing a Maintenance Page where people can store the description of what it will say in a Resource file, at this point in the requirement they dont even know if the text will be pure text or will have tags like <a></a>. So at this point I have to assume it will be the case.
This proyect have been made in Webforms framework 3.5 in VS2010.
For simplicity sake I'll reveal the relevant parts:
<article>
<img alt="an image" src="Images/logo.jpg"/>
<h2>Site under Maintenance</h2>
<div>
<p id="Description"></p>
</div>
</article>
<script src="Includes/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "MaintenanceSite.aspx/GetMaintenanceDescription",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Description").text(msg.d);
}
});
});
</script>
Backend:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetMaintenanceDescription()
{
string mensaje = HttpUtility.HtmlEncode(Resources.MaintenanceDescription);
return mensaje;
}
The problem is, Im receiving this on my paragraph:
<To href="">Contact Us</a>
(without the spaces as stack overflow is parsing the html correctly).
What am I missing?
There's two issues here. Firstly you need to remove the call to HtmlEncode() in the C# logic to return a plain HTML string. Secondly you need to use jQuery's html() method to display it instead of text(), as the latter will again encode the HTML.
string mensaje = Resources.MaintenanceDescription;
$("#Description").html(msg.d);

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.

using ajax in asp.net 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.

Reading XML data from ASMX webservice for Jquery autocomplete

Me and ASMX web services do not get on. We argue. She brings up arguments we had in the past. It's a pain. Our relationship is on the rocks!
I have an ASMX web service, which I haven't serialised with the Newtonsoft library (as explained why here: http://encosia.com/2011/04/13/asp-net-web-services-mistake-manual-json-serialization/). It looks like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
var dict = AtomicCore.CityObject.GetCitiesInCountryWithStateAutocomplete(isoalpha2, prefixText);
string[] cities = dict.Values.ToArray();
return cities;
}
Simple enough right? It return this when searching for new:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<string>New Orleans, Louisiana</string>
<string>New York, New York</string>
</ArrayOfString>
I was expecting JSON, but after a bit of reading, it seems I shouldn't try and serialise the output - it should just happen right? Anyway, so I have the following JQuery on the frontend:
$('#<%=txtCity.ClientID%>').autocomplete('<%=ResolveUrl("~/AtomicService/Assets.asmx/GetCitiesWithState")%>', {
dataType: 'json',
httpMethod: 'POST',
contentType: 'application/json; charset=utf-8',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.d.length; i++) {
rows[i] = { data: data.d[i], value: data.d[i].Value, result: data.d[i].Value };
}
return rows;
},
formatItem: function (row, i, n) {
return row.Value;
},
extraParams: {
minChars: 2,
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
maxRows: 20,
prefixText: function () {
return $('#<%=txtCity.ClientID%>').val()
}
},
max: 20
}).result(function (event, data, formatted) {
if (data) {
alert(data['Key']);
}
});
I can see the calls using Chrome:
And yet stuff all happens! There is no Jquery errors, no fireworks, no anything. She is ignoring me.
At first I was blaming the webservice, but I think this may have more to do with how I'm parsing and formatting the data in jquery.
So, my question is, what am I doing wrong and how can I make the autocomplete work correctly?
Help appreciated :)
EDIT: It may not be helpful, but this is what I see in Fiddler:
The jQuery UI autocomplete does not anymore use the formatItem method. That and many other such methods were present in autocomplete's earlier version that was a plugin here
I have rewritten your code using the jQuery UI's autocomplete and it works for me with the below htm and asmx files.
Refer to the demos on the jQueryUI autocomplete for more methods you could use.
I have used the json2.min.js from www.json.org
Also I have added the [System.Web.Script.Services.ScriptService] attribute to the Service1 class so that it could directly be invoked from jQuery as a json web service.
These articles helped me:
ASMX and JSON – Common mistakes and misconceptions
Using jQuery to Consume ASP.NET JSON Web Services
3 mistakes to avoid when using jQuery with ASP.NET AJAX
The htm file
<!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>
<title>jQuery to ASMX</title>
<link rel="Stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/cupertino/jquery-ui.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://localhost/Scripts/json2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#txtInput").autocomplete({
source:function (request, response) {
var paramters = {
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
prefixText: request.term
};
$.ajax({
url: 'Service1.asmx/GetCitiesWithState',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramters),
success: function(data) {
response($.each(data.d, function(index, value) {
return {
label: value,
value: index
}
}));
}
});
},
minLength:2,
delay:500
});
});
</script>
<p>
Hello, World!</p>
<label for="txtInput">
Enter the string here:</label><input type="text" id="txtInput"/>
</body>
</html>
The asmx file
using System.Web.Script.Services;
using System.Web.Services;
namespace jQueryAutoCompleteBackEnd
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service1 : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
return new string[] { "New Orleans, Lousiana", "New York, New York" };
}
}
}
The reason that the asmx webmethod is returning XML rather than JSON is because the HTTP method is GET rather than POST.
In order for the autocomplete plugin to use POST you'll have to implement the source parameter using a callback function, see here

jQuery AJAX call to ASP.NET WebMethod errors constantly

I have a really simple AJAX method inside my Default.aspx.cs and it looks like this:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
And the Default.aspx looks like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="http://192.168.1.2/tizma.com/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(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: AjaxSucceeded,
error: AjaxFailed
});
});
});
function AjaxSucceeded(result)
{
alert(result.d);
}
function AjaxFailed(result)
{
alert(result.status + " " + result.statusText);
}
</script>
</head>
<body>
<div id="Result">Click me</div>
</body>
</html>
The problem is when I click the div the ajax error function is all that is ever called with a 200 status.
What am I doing wrong?
Not sure if it's causing the problem but you have a line which reads:
data: "{}",
it should read:
data: {},
or you can omit the line altogether as it's an optional parameter to the method call. You are currently setting it to a string value when it actually expects parameters for the webmethod which might cause problems.
Also, the lines reading:
contentType: "application/json; charset=utf-8",
dataType: "json",
seem unnecessary to me because for starters, it isn't obvious that your webmethod is actually returning json. I think it's just returning a string. Try removing those three lines alltogether and see if it doesn't just start working.

Categories