Using jQuery to call a web service - c#

I have created a web service which takes a username and password as parameters and returns a list of children in JSON (the user is a Social Worker). The web service is hosted locally with IIS7. I am attempting to access the web service using javascript/jquery because it will eventually need to run as a mobile app.
I'm not really experienced with web services, or javascript for that matter, but the following two links seemed to point me in the right direction:
http://williamsportwebdeveloper.com/cgi/wp/?p=494
http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
This is my html page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="TestWebService.aspx.cs" Inherits="Sponsor_A_Child.TestWebService" %>
<asp:Content ID="Content1" ContentPlaceHolderID="stylesPlaceHolder" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.js">
$(document).ready(function () { });
function LoginClientClick() {
$("#query_results").empty();
$("#query_results").append('<table id="ResultsTable" class="ChildrenTable"><tr><th>Child_ID</th><th>Child_Name</th><th>Child_Surname</th></tr>');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost/PhoneWebServices/GetChildren.asmx?op=GetMyChildren",
data: '{ "email" : "' + $("#EmailBox").val() + '", "password": "' + $("#PasswordBox").val() + '" }',
dataType: "json",
success: function (msg) {
var c = eval(msg.d);
alert("" + c);
for (var i in c) {
$("#ResultsTable tr:last").after("<tr><td>" + c[i][0] + "</td><td>" + c[i][1] + "</td><td>" + c[i][2] + "</td></tr>");
}
}
});
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<div id="LoginDiv">
Email: <input id="EmailBox" type="text" /><br />
Password: <input id="PasswordBox" type="password" /><br />
<input id="LoginButton" type="button" value="Submit" onclick="LoginClientClick()" />
</div>
<div id="query_results">
</div>
</asp:Content>
And this is my web service code:
[WebMethod (Description="Returns the list of children for whom the social worker is responsible.")]
public String GetMyChildren(String email,String password)
{
DataSet MyChildren=new DataSet();
int ID=SocialWorkerLogin(email, password);
if (ID > 0)
{
MyChildren = FillChildrenTable(ID);
}
MyChildren.DataSetName = "My Children"; //To prevent 'DataTable name not set' error
string[][] JaggedArray = new string[MyChildren.Tables[0].Rows.Count][];
int i = 0;
foreach (DataRow rs in MyChildren.Tables[0].Rows)
{
JaggedArray[i] = new string[] { rs["Child_ID"].ToString(), rs["Child_Name"].ToString(), rs["Child_Surname"].ToString() };
i = i + 1;
}
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(JaggedArray);
return strJSON;
}
I followed the examples in the provided links, but when I press submit, only the table headers appear but not the list of children. When I test the web service on it's own though, it does return a JSON string so that part seems to be working. Any help is greatly appreciated :)
EDIT: Thanks to slash197 I discovered the problem. I get the error:
"XMLHttpRequest cannot load http://localhost/PhoneWebServices/GetChildren.asmx?op=GetMyChildren. Origin http://localhost:56018 is not allowed by Access-Control-Allow-Origin."
In Chrome's console. I'm guessing this has something to do with the URL, but when I try that URL in my browser it works fine.

the problem with
"XMLHttpRequest cannot load http://localhost/PhoneWebServices/GetChildren.asmx?op=GetMyChildren. Origin http://localhost:56018 is not allowed by Access-Control-Allow-Origin."
is, localhost and localhost:56018 are per definition two different domains, and Ajax Requests are per default only possible through the same domain.
A best approach for that would be, to run both services on the same port or by using a proxy, which delivers the content from port 56018 to the default localhost port 80. Could be realized through a Rewrite Rule or via an own service which is running, besides your webservice "client".

Related

How can I perform an ajax call to .aspx.cs

I've spent 4 days trying to make an ajax call to my .aspx.cs. In the best case, I got answer in html format. I don't understand why that happened, maybe I have to add some lib from NuGet or write something in web.config?
What I tried:
[HttpPost] [HttpGet]
[WebMethod]
jQuery ajax call
change url
my first app was a sample from VS with razor pages, I thought the problem was in using razor, so I created new project - a empty web application, but I still got the same answer from server in html format.
What I want to get:
My app imitates a vending machine. A user click on buttons with coins and coins have to increase on server side. (BtnAddCoin()) Also user's coins are always showing on a panel. (ShowInsertedCoins())
ClientSide.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ClientSide.aspx.cs" Inherits="VendingMachine.ClientSide" Async="true" AsyncTimeout="60" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="stylesheet" href="StyleSheet.css" />
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function AddCoin(coin) {
alert(coin);
var val1 = coin;
$.ajax({
type: "POST",
url: "/ClientSide.aspx/BtnAddCoin",
data: '{coin: "' + coin + '" }',
dataType: "text",
success: function (data) {
alert("AddCoin" + data);
},
error: function (req, status, error) {
alert(error + status);
}
}).done(function (result) { ShowInsertedCoin(); });
}
function ShowInsertedCoin() {
var insertedCoins = document.getElementById('InsertedCoins');
alert('ShowInsertedCoin');
$.ajax({
type: "GET",
url: "/ClientSide.aspx/ShowInsertedCoins",
dataType: "text",
data: {},
success: function (data) {
alert("ShowInsertedCoin " + data);
insertedCoins.textContent = data;
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
</form>
<div>
<h1>Coffee machine</h1>
</div>
<div>
<div>
<p> Add coins: </p>
<div>
<div>
<a id ="coin1" onclick="AddCoin(1)"> 1 </a>
<a> 2 </a>
<a> 5 </a>
<a> 10 </a>
</div>
</div>
<div>
<p id="InsertedCoins" ><%=ShowInsertedCoins()%> </p>
</div>
</div>
</div>
</body>
</html>
ClientSide.aspx.cs
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 VendingMachine
{
public partial class ClientSide : System.Web.UI.Page
{
static int coins = 10;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ShowInsertedCoins()
{
return "You inserted: " + coins.ToString();
}
[WebMethod]
public void BtnAddCoin(int coin)
{
coins = +coin;
//ShowInsertedCoins();
}
}
}
So, how I can do an ajax call to .aspx.cs with jQuery or js?
Why do I get html format when my function has to return a string?
Thanks for your attention and help.
Lots of issues here.
First issue?
You have this static value for the page class:
static int coins = 10;
You can't really control, or use or have static values in a class. The MAIN reason is such values will apply to all users of the site - not just the one user.
You can as a general rule call, use, consume static classes. In fact in vb.net, we OFTEN create a Module, and inside we have our boatload of helper routines, and routines that we freely call that library of code. While each of the routines can freely use local values, you can NOT use variables global to that module, since no instance of the class is being created, and as a result, multiple users will/would be able to set such values - and overwrite values used by other users. Worse yet, how long does the server persist such static values?
Answer: it is a total Las Vegas gamble.
this means to persist that coin count, we can choose one of MANY possible ways to persist that value.
We can have a global JavaScript variable hold the value.
We can use a control like text box to hold the value (and hide it)
We can use a hidden control (so ViewState will hold the value).
We can use ViewState directly to the hold the value (client side persisting), but is managed by server side code.
We can use session() to hold the value (server side persisting)
Over the years, we see "many" attempts to pass, share, persist data vales in a static class. It sometimes works, and often during development it "seems" to work, but the instant you deploy to a real working site, it blows up in a huge ball of flames.
So, using a static class to hold a Hodge podge of code? Sure, no problem, and that's quite much what we do in c# to obtain general "code module" of routines that we need throughout the applcation. But, be a vb.net module, or in c# a static class? Any concept of global values to that static class MUST be taken off the table and NOT used!!
Ok, so let's cook up a working example. We first have to choose a place/spot to hold and persist our coin count.
Hum, we have many choices. However, since this example code involves server side code. Then let's use session.
I mean, it would kind of defeat this whole example if we write the code 100% client-side JavaScript (which is not all that bad of a idea). However, since we attempting to learn, and use a web method?
Then let's wire this up using a web method. (as noted, we really don't need to use any server-side code here).
So, if we going to use session() to persist the value, then on first page load, we setup our coin count with a starting value of 10.
Also, WHEN you use/call/consume a web method of the page? There is NOT a instance of the page class. As a result, ANY AND ALL web methods must be static. In fact, it means really don't care if we placed the web method in the current page, is some ascx file, or wherever. Since the web page is NOT being posted back to the server, then all of the controls, values and things on that web page are STILL sitting on your desktop, and there is no copy of the web page in existence on the server side.
Next up:
data: '{coin: "' + coin + '" }',
dataType: "text",
So, you have some jason data, yet on the next line you saying we going to use text? Nope!!! If you going to pass json data the method, it going to return such json data back. Same goes if you choose xml, or whatever.
So, you can't pass json data, but then on the next line state we going to use text!!!!!
Ok, so our server side code now becomes this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// setup starting coin count
Session["CoinCount"] = (int)0;
}
}
[WebMethod(enableSession: true)]
public static void BtnAddCoin(int coin)
{
int MyCoins = (int)HttpContext.Current.Session["CoinCount"];
MyCoins += coin;
HttpContext.Current.Session["CoinCount"] = MyCoins;
Debug.Print("coins = " + MyCoins.ToString());
}
[WebMethod(enableSession: true)]
public static string ShowInsertedCoins()
{
int MyCoins = (int)HttpContext.Current.Session["CoinCount"];
return "You inserted: " + MyCoins.ToString();
}
Now, for client side, DO NOTE that when you use json format, then the return value/results are of the ".d" property of the web method. This is a asp.net thing, and it just the way it works.
So, now our client side code;
<div>
<div>
<p>Add coins: </p>
<div>
<div>
<a id="coin1" onclick="AddCoin(1)">1 </a>
<a>2 </a>
<a>5 </a>
<a>10 </a>
</div>
</div>
<div>
<p id="InsertedCoins"></p>
</div>
</div>
</div>
<script>
function AddCoin(coin) {
$.ajax({
type: "POST",
url: "/CoinCount.aspx/BtnAddCoin",
data: JSON.stringify({ coin: coin }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
// alert("AddCoin" + data);
ShowInsertedCoin();
},
error: function (req, status, error) {
alert("x" + error + status);
}
}).done(function (result) { ShowInsertedCoin(); });
}
function ShowInsertedCoin() {
var insertedCoins = $('#InsertedCoins');
$.ajax({
type: "POST",
url: "CoinCount.aspx/ShowInsertedCoins",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {},
success: function (data) {
insertedCoins.text(data.d);
}
});
}
</script>
Next up?
How did "form2" get inserted into this page?
If you create a new aspx page, (web forms), then the last gazillion pages will have by default form1, and BIG flag that you have form2 here.
Anyway, the above should work. Note that you not only are sending json data, but you as a general rule need to add the content type, and you had this missing:
contentType: "application/json; charset=utf-8",
Also, so far we only added a click event for the "1", and you have to do the same for the other 3 values you have.
As other people already commented, it's recommended to use newer technologies, other than Webforms, but if you want to continue using it or it's an project of your work or something related, here's how I normally do in Javascript:
$.ajax({
method: "POST",
url: "ClientSide.aspx/BtnAddCoin",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
obj: JSON.stringify(data)
}),
success: function (response) {
let return = JSON.stringify(response.d);
// something
},
error: function (ex) {
// something
console.log(ex.Message)
},
beforeSend: function () {
// something
},
complete: function () {
// somethin
}
});
And for the C# file, every time you want to make an webmethod, that method need to be public and static, just like that (at least I learned that every time needs to be static):
[WebMethod]
public static string BtnAddCoin(int newCoin)
{
return newCoin;
}
Try and see if that helps

DNN: HttpContext.Current.Session not Working

I'm not an expert in .NET programming and I'm trying to solve this problem but no success.
We decided to revamp our old website and part of it is to switch theme. But we have a function from old that we can't move to the new theme.
Our old website has a function that will get user's session code, so that if they move to our affiliate website via url, they will be automatically logged in.
This is the code from our old theme...
OLD THEME CODE
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="/Home.ascx.cs" Inherits="Mandeeps.DNN.Skins.Tucson.Tucson" %>
<%# Register TagPrefix="dnn" Namespace="DotNetNuke.Web.Client.ClientResourceManagement" Assembly="DotNetNuke.Web.Client" %>
<script type="text/javascript">
var onetimeurl = "<%#HttpContext.Current.Session["OneTimeURL"]%>";
$(document).ready(function() {
$('.financials_link').attr("href", "https://sub.domain.com?authToken=" + onetimeurl);
$('.financials_link').attr("target", "_blank");
var service = $.ServicesFramework(-1);
$.ajax({
type: "GET",
url: service.getServiceRoot("WebAuthModule") + "webauth/getauthtoken",
beforeSend: service.setModuleHeaders,
dataType: "json"
}).done(function(a) {
a && $(".financials_link").attr("href", "https://sub.domain.com?authToken=" + a)
});
});
</script>
It's working great. But when moved the code to the new theme, the code is not showing up and its breaking the page's layout. And I'm getting this error.
Line 20: Error BC30516: Overload resolution failed because no accessible 'ToString' accepts this number of arguments.
NEW THEME CODE
<%# Control Language="vb" AutoEventWireup="false" Explicit="True" Inherits="DotNetNuke.UI.Skins.Skin" %>
<script type="text/javascript">
var onetimeurl = "<%#HttpContext.Current.Session["OneTimeURL"]%>"; <!--LINE 20-->
$(document).ready(function() {
$('.financials_link').attr("href", "https://sub.domain.com?authToken=" + onetimeurl);
$('.financials_link').attr("target", "_blank");
var service = $.ServicesFramework(-1);
$.ajax({
type: "GET",
url: service.getServiceRoot("WebAuthModule") + "webauth/getauthtoken",
beforeSend: service.setModuleHeaders,
dataType: "json"
}).done(function(a) {
a && $(".financials_link").attr("href", "https://sub.domain.com?authToken=" + a)
});
});
</script>
Noticed on the first line, I added the control codes because that is the only thing I think is different from each other. The rest are pretty much the same.
What I've done so far is I decompiled the Home.ascx (.dll) and looked for the OneTimeURL, but I wasn't able to find it.
I wish you guys can spot the problem so I can fix this.
It seems odd to me that you are saying the old one is C# and the new one is VB??
But given what I see above, try this, just change the square brackets to parens, so the new line 20 is:
var onetimeurl = "<%#HttpContext.Current.Session("OneTimeURL") %>";
If that doesn't work, then add try adding this function at the bottom.
<script runat="server">
Public Function GetSession() As String
Return HttpContext.Current.Session("OneTimeURL")
End Function
</script>
And then line 20 would need to be:
var onetimeurl = "<%#GetSession() %>";

asp.net dropdownlist caching for Huge data

I have to bind nearly 50k records to my asp.net dropdownlist and it has to be searchable. What is the best way to do implement it . Are there any caching techniques so that the list loads as we scroll?Appreciate the suggestions.
Please advise.
I'd recommend taking advantage of jQuery's autocomplete plugin:
https://jqueryui.com/autocomplete/
It's configurable and has autocomplete search out of the box. It can also consume your remote data source (though you might consider a paginated API response):
http://api.jqueryui.com/autocomplete/#option-source
You can achieve this by use of web service.
first of all add following code in your aspx page.
<div>
<input type="text" value="" id="tbCountries" />
</div>
Now, Create your Web service using following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.>WebService {
[WebMethod]
public List<string> ShowCountryList(string sLookUP)
{
List<string> lstCountries = new List<string>();
string sConnString = "Data Source=DNA;Persist Security Info=False;" +
"Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;";
SqlConnection myConn = new SqlConnection(sConnString);
SqlCommand objComm = new SqlCommand("SELECT CountryName FROM Country " +
"WHERE CountryName LIKE '%'+#LookUP+'%' ORDER BY CountryName", myConn);
myConn.Open();
objComm.Parameters.AddWithValue("#LookUP", sLookUP);
SqlDataReader reader = objComm.ExecuteReader();
while (reader.Read()) {
lstCountries.Add(reader["CountryName"].ToString());
}
myConn.Close(); return lstCountries;
}
}
Finally, Create jquery Method for bind Textbox with webservice,
<script>
$(document).ready(function() {
BindControls();
});
function BindControls() {
$("#tbListOfCountries").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/ShowCountryList",
data: "{ 'sLookUP': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return { value: item }
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1 // MINIMUM 1 CHARACTER TO START WITH.
});
}
</script>
In the backend, create a controller action (if you are using ASP.NET MVC) or a page method (if you're using ASP.NET Web Forms) that receives a searchTerm parameter and returns an array of the top (say, 100) results.
In the frontend, use a typeahead / autocomplete plugin such as this one. When the user sets the search term, perform an Ajax request against the backend and display the results. When performing the Ajax request, you can also enable and configure caching. No more optimization shall be needed.
Use AutoComplete textbox and set datasource from remote API especially when working with huge dataset. This will avoid your application UI getting hanged on every character search.
Ref the Link: https://github.com/ghiden/angucomplete-alt
depends on where the list items are coming from.
if they are coming from a list or database just append them then use javascript to search the list.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="ui-widget">
<asp:TextBox ID="txtDepartment" runat="server" ClientIDMode="Static" />
</div>
</form>
<script>
$(function () {
$("[id$=txtDepartment]").autocomplete({
source: function (request, response) {
$.ajax({
url: "FetchDropdownList.aspx/GetDepartment",
data: "{'departmentName':'" + document.getElementById('txtDepartment').value + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
</script>
</body>
</html>
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
private static List<Department> GetDepartment()
{
List<Department> departments = new List<Department>();
for (int i = 0; i < 10000; i++)
{
Department department = new Department();
department.Id = i;
department.Name = "Department " + i.ToString();
departments.Add(department);
}
return departments;
}
[WebMethod]
public static List<Department> GetDepartment(string departmentName)
{
int totalDepartments = GetDepartment().Count;
List<Department> departments = GetDepartment().Where(d => d.Name.ToLower().StartsWith(departmentName.ToLower())).Take(20).ToList();
return departments;
}
I had same problem like you and I used RadAutoCompleteBox. It has many
client-side and server-side events that help you to handle various situations. It's very comfortable for ASP.NET projects.
I see two immediate solution for this.
As other has suggested usign ajax to search related item as user types and show them.
On page load get all your data and store them in javascript variable then you can perform search on that variable as user types and bind search result to dropdown list.
Similar to this one:
Definitely any Autocomplete implementation will work in your scenario.
Solution 1: Use Autocomplete select box
If you don’t want to waste bandwidth or want to support devices with
low specification, you should go for AutoComplete with server side
data fetching.
If you want high usability and don’t care about the bandwidth,
you can use autocomplete with local data (Fetch 50k records one time
and bind to the autocomplete). But to make sure that you don’t paint
all these into DOM at a single time. You need to limit the records
being shown at a particular time.
Solution 2 : Use select with virtualization
But if you want to give the best of the usability to your
clients, you should go with a solution where your select box is
virtualized and the data loaded into DOM on scrolling of the select box. By virtualization you are making sure that only those
items are getting pushed to DOM which are being shown in the
screen at that point of time.
You can find a jQuery based virtual select here
Similar implementation in React here

How do I create a single-page ASP.NET application that submits info to a database?

Ok, I know this is embarassing since I've been working as a web developer with ASP.NET for months, but I used to starting with a largely prepackaged ASP.NET MVC site with routing, controllers, etc., and extending it from there. All I need to do right now is creating a single-page ASP.NET page that submits a form to the database.
I already have my table in the database
CREATE TABLE stuff ( field1 VARCHAR (100), field2 VARCHAR (100) );
and I have a form in my HTML
<form id="myform">
<input type="text" name="field1"/>
<input type="text" name="field2"/>
<input type="submit"/>
</form>
and I have a function
$('#myform input[type="submit"]').click(function(){
var that = this;
$.ajax({
url: '????',
method: 'POST',
data: new FormData($(that).closest('form')[0]),
success: function() { alert("Well, at least this succeeded"); }
});
I started in Visual Studio with a "ASP.NET Empty Web Application Visual C#" but I seriously don't know what type of file I need to right-click-Add to the project to handle this. All I'm trying to do is a simple insertion of the inputs field1 and field2 into their corresponding columns in the database. I can't find any resources of how to build an ASP.NET page from scratch and all the books I've ever read start with a template that has everything hooked up, so ...
Can someone give me a hint of how to connect the dots here?
Here is the Code
web method must be public and static
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<link rel="Stylesheet" href="StyleSheet.css" />
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function (e) {
alert('Data Saved')
var commentsCorrespondence;
var ddlST = $('#ddlStatus option:selected').val();// get dropdown selected value in ddlST variable
var chkbox = $('#ChkValue').val();// get checkbox value in chkbox
var Date = $('#txtDate').val();//get textbox value in date variable
$.ajax({
type: "POST",
url: "AutoCompleteCity.aspx/SaveData", //this is the url from which you call your web method ! in my case its /Default.aspx and method name is SaveData
data: "{'status': '" + ddlST + "','chkBoxValue': '" + chkbox + "','DueDate': '" + Date + "'}",// These are the method parameters in my case 'status' , 'chkBoxValue' and 'DueDate' are parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('Data Saved'),
failure: function (response) {
Message = response.d;
}
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:DropDownList ID="ddlStatus" runat="server"></asp:DropDownList>
<asp:CheckBox ID="ChkValue" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
<br />
<br />
</div>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class AutoCompleteCity : System.Web.UI.Page
{
[WebMethod]
public static void SaveData(string status, string chkBoxValue, string DueDate)
{
List<string> Emp = new List<string>();
string query = string.Format("Insert Into [Table] Values ({0},{1},{2})", status, chkBoxValue, DueDate);
using (SqlConnection con = new SqlConnection("your Connection string"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
Create a WebMethod in cs file of the same page
[WebMethod]
Public static bool FxName(string field1, string field2){
// Do the code here for saving
}
in ajax
$('#myform input[type="submit"]').click(function(){
var that = this;
$.ajax({
url: 'pagename.aspx/FxName',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {"field1": valueoftextbox,"field2":valueoftextbox},
success: function() { alert("Well, at least this succeeded"); }
});
Given the template you're using, I think a controller from ASP.NET Web API will be more appropriate than WebMethods (which were introduced in .NET 3.5 and haven't changed since...).
Add an ApiController to your project:
public class FooController : ApiController
{
[HttpPost]
public IHttpActionResult PostForm(FormInput input)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// You'll have to create the repository class as well as inject it
// into your controller. If you don't know what I'm talking about,
// google "dependency injection asp.net webapi" for more info.
_repository.SaveFormDataToDb(input.Field1, input.Field2);
return Ok();
}
}
You'll also need to create the input model:
[DataContract]
public class FormInput
{
[DataMember]
[Required]
public string Field1 { get; set; }
[DataMember]
[Required]
public string Field1 { get; set; }
}
The [DataContract] and [DataMember] attributes are from System.Runtime.Serialization. [Required] is from System.ComponentModel.DataAnnotations, and will work in conjunction with ModelState.IsValid() to validate input - you can add a bunch of other attributes too (or write your own!) to specify other rules than just required fields.
Depending on how you're planning to host this (in IIS or not) the way you hook up the dependency injection, routing etc is a little different, but the tutorials on asp.net are legio.
Good luck! :)

How to call webservice in HTML page using JQuery?

i have WebService that get 2 string and return if they equals
WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "Validate the login credentials")]
public bool Validate(string UserName, string Password)
{
if (Password == "test" && UserName == "test")
return true;
else
return false;
}
}
and i have html page that call this WebService and need to return the Result
<html lang="en-US">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var Surl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
$(document).ready(function () {
$("input#submit").click(function (event) {
//var uid = document.getElementById("UserName").value;
//var pwd = document.getElementById("Password").value;
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
$.ajax({
ServiceCallID: 1,
url: Surl,
type: 'POST',
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
returnVal = result.d;
alert(returnVal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
returnVal = '';
}
});
});
});
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" />Connet to my WS
</form>
</body>
</html>
this what i get:
and i try this, still same problem....
<script>
function XX() {
alert("in");
$.post('http://localhost/WS_HTML/Service1.asmx/Validate', { username: 'test', password: 'test' }, function (response) {
response; // Here is response
alert(response);
});
}
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" onclick="XX();" />Connet to my WS2
</form>
</body>
</html>
i try with $.get - and same.... Nothing happens....
from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,
but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>
Request format is unrecognized for URL unexpectedly ending in '/Validate'.
I swear to God that for several days I break my head and can not figure out why it does not work
):
thanks,
You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)
Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).
<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript">
var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
function submitMyForm(){
// Define your datas
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
// Create and send the request
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
// Log with console.log() or alert if you want...
console.log('State of my request changed! ');
if (XMLHttpRequest.DONE === request.readyState) {
console.log(request.responseText);
}
}
request.open('POST', myUrl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
</script>
</head>
<body>
<form>
<button onclick="submitMyForm()" >Connect to my WS</button>
</form>
</body>
</html>
I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).
For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.
I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).
Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum
Hope I help you.
Why not use $.post() ?
$.post('/your/service/url/', {username:'asd', password:'qwe'}, function(response){
response; // Here is response
});

Categories