Sending a string Value to the WebMethod - asp.net

function EmpCode(empCode) {
var queryString = "";
var hasQuerystring = document.URL.indexOf('?');
if (hasQuerystring != -1) {
queryString = document.URL.substring(hasQuerystring + 1, document.URL.length);
if (queryString == 'id=1') {
$.ajax({
type: "POST",
url: "EmployeeBasicInfo.aspx/CheckEmpCode",
data: "{'empCode':" + empCode + "}",// Sending empCode which is a string
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var errorMsg = (msg.d);
if (errorMsg != 'NA') {
alert(errorMsg);
}
}
});
}
}
}
Here is my WebMethod
[WebMethod]
public static string CheckEmpCode(string empCode)
{
string empCod = "";
EmployeeFactory empFactory = new EmployeeFactory();
empCod = empFactory.CheckCode(empCode);
return empCod;
}
When i send the empCode as '11479' 0r any integers from Ajax the web method is calling. when i send the empcode as "C1026" or any string with characters then the webmethod is not getting called..
Please suggest me how to pass empCode which is having string value.

Put quotes around the EmpCode.Currently you are sending:
data: {'empCode': C1026}
You need to send:
data: {'empCode': 'C1026'}

Related

How to pass an array to asmx web service via JSON?

I want to pass array value to my web service file. But it throws the following error
setDeleteFiles
Test
The test form is only available for methods with primitive types as parameters.
Here is my jquery code
$('#btnDeleteFiles').click(function () {
var filesPaths = [];
i = 0;
$("input:checkbox[name=filed-checkedbox]:checked").each(function () {
filesPaths[i] = $(this).val();
i++;
});
//alert("filesPaths = " + filesPaths)
var location = $('#ddlLocation option:selected').text();
alert("Location = "+location)
$.ajax({
method: 'post',
url: "GetAllFolderDetails.asmx/setDeleteFiles",
data: {
location: location,
fileNames: filesPaths
},
dataType: "json",
success: function (data) {
window.location.reload(true);
//alert("Success");
},
error: function (result) {
alert("Error");
}
});
});
GetAllFolderDetails.asmx code
[WebMethod]
public void setDeleteFiles(string location, string[] fileNames)
{
var locationID = 0;
var domain = "domain";
var username = "xxx"; //username
var Password = "***"; //password
Debug.WriteLine("Location = "+location);
Debug.WriteLine("fileNames = " + fileNames);
using (new ImpersonateUser(username , domain, Password))
{
Debug.WriteLine("Files names = "+ fileNames);
foreach (string file in fileNames)
{
FileInfo files = new FileInfo(file);
files.Delete();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize("Files are successfully Deleted"));
}
}
Note
If I pass a string as a parameter without an array, it is working fine
Use the following
data: JSON.stringify({ location: location, fileNames: filesPaths }),
contentType: "application/json; charset=utf-8",
dataType: "json",
and change the input parameter datatype as List<string> instead of string[]
Just remove
dataType: "json",
from your ajax call.
and also check in your asmx file that it is decorated with
[System.Web.Script.Services.ScriptService]
try this.

asp.net web forms [WebMethod]

I have a problem with my [WebMethod] when I return Json data List<Contract> from DB using Entity Framework
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "/Pages/App/Docs.aspx/PopulateDataByJquery",
data: "{pageNo: " + pageIndex + ", noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
This my WeMethod.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Contract> PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
return data;
}
I every time getting ajax error, help me please! I don't know how it fix.
You have to make some changes to your ajax call and WebMethod
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "Docs.aspx/PopulateDataByJquery",
data: "{pageNo: pageIndex, noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
Change your WebMethod
[WebMethod]
public static string PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
JavaScriptSerializer TheSerializer = new JavaScriptSerializer()
var TheJson = TheSerializer.Serialize(data);
// for this you need to add using System.Web.Script.Serialization;
return TheJson;
}
For more read this

calling webmethod using jquery

I am having two asp textboxes, TextBoxPicPostCode and TextBoxPicAddress.
The goal of this task is that when i enter a post code in TextBoxPicPostCode and the focus gets lost from this TextBox it should automatically populate TextBoxPicAddress using the method in code behind.
The method getadd() in .cs code works fine and uses google api but i am not getting an idea how to use jquery ajax with it.
Code-Behind
public void getadd()
{
string address = "";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://maps.google.com/maps/api/geocode/xml?address=" + TextBoxPicPostCode.Text + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
TextBoxPicAddress.Text = address;
}
}
JavaScript
<script type="text/javascript">
function submit() {
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx.cs/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Markup
<asp:TextBox ID="TextBoxPicPostCode" runat="server"
CssClass="time"
onblur="submit();">
</asp:TextBox>
<asp:TextBox ID="TextBoxPicAddress" runat="server"
CssClass="address">
</asp:TextBox>
Make these changes
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
// change the function name from 'submit' here and at markup
function FetchAddress() {
//passing postalCode as string.
//Make sure that 'postalCode' is the parameter name at the webmethod
var dataValue = "{ 'postalCode' : '" + $('.time').val() + "'}";
//would be worthwhile to read about JSON.stringify, its the standard method
//var dataValue = JSON.stringify({ postalCode: $(".time").val() });
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd", // .cs is not required
data: dataValue,
contentType: 'application/json', //charset is not required
//dataType: 'json', // not required
success: function (result) {
var data = result.hasOwnProperty("d") ? result.d : result;
//alert("We returned: " + result.d);
// now we are assigning the return value to TextBoxPicAddress
$(".address").val(data);
}
});
}
</script>
Code-behind
//1. webmethod attribute required
[System.Web.Services.WebMethod]
//2. web methods should be static
//ref: http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
//3. return type string is needed
// because we need to fetch the return on the ajax callback
//4. we need to pass TextBoxPicPostCode as a parameter
// because we need to fetch the return on the ajax callback
public static string getadd(string postalCode)
{
string address = "No Address found!";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
var remoteXml = "http://maps.google.com/maps/api/geocode/xml?address="
+ postalCode + "&sensor=false";
xDoc.Load(remoteXml);
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
}
return address;
}
At markup, change the event as onblur="FetchAddress();"
P.S: No time to type all the changes made in detail, so added as comment
.cs is Not Required
and
public void getadd()
Should be Static
so
[System.Web.Services.WebMethod]
public static void getadd()
JScript
<script type="text/javascript">
function submit()
{
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
EDIT:
You Can't Use Controls Inside Static method. You nee to Refer This:
Using Jquery Ajax Call
Using AutoCompleteExtender
HTML
Javascript
`
function danish() {
var code = $("#<%=TextBoxPicPostCode.ClientID %>").val();
$.ajax({
type: "POST",
url: "GoogleAPI.aspx/getadd",
contentType: 'application/json; charset=utf-8',
data: '{code: "' + code + '"}',
dataType: 'json',
success: function (result) {
$("#<%=TextBoxPicAddress.ClientID %>").autocomplete({ source: result.d });
}
});
return false;
}
</script>`
Codebehind
using System.Web.Services;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
[WebMethod]
public static List<string> getadd(string code)
{
string address = "";
List<string> lst = new List<string>();
XmlDocument xDoc = new XmlDocument();
var jsonSerialiser = new JavaScriptSerializer();
try
{
HttpWebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
xDoc.Load(#"http://maps.google.com/maps/api/geocode/xml?address=" + code + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
for (int i = 0; i < distanceX.Count; i++)
{
lst.Add(distanceX[i].InnerXml);
address = address + distanceX[i].InnerXml;
}
}
}
catch (Exception ex)
{
throw ex;
}
return lst;
}

How to handle FormData AJAX post (file with additional params) with asp.net WebMethod

Having trouble handling a jQuery AJAX post of FormData to an ASP.net 4 Web service WebMethod.
<input id="ipt_file" type="file" />
<a href='#' onclick="UploadFile();" data-role='button'>Upload</a>
var UploadFile = function () {
var file_object = $('#ipt_file')[0].files[0];
var form_data = new FormData();
form_data.append('job_id', '123456');
form_data.append('job_name', 'xyx');
form_data.append('job_file', file_object);
var xhr_upload = $.ajax({
type: "POST",
headers: { "Cache-Control":"no-cache", "Content-Type":"multipart/form-data" }, // also tried without these
url: "../MyServices.asmx/Upload",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function (msg) {
if (typeof (msg) === "object") {
var _upload = $.parseJSON(msg.d);
alert(_upload.status + ': ' + _upload.msg);
};
}
});
};
public class FileUploadRequest
{
public string job_id { get; set; }
public string job_name { get; set; }
public HttpPostedFile job_file { get; set; }
}
[WebMethod]
public string Upload(FileUploadRequest x)
{
string str_response = string.Empty;
if (x.job_file.ContentLength > 0)
{
str_response = "{\"status\":1,\"msg\":\"" + x.job_id + ", " + x.job_name + ", " + x.job_file.FileName + "\"}";
}
else
{
str_response = "{\"status\":0,\"msg\":\"FAIL"\}";
};
return str_response;
}
Must not be handling the FormData object parameter properly; here I instantiated a custom class, but all I get back from the server is 500 errors (also tried a generic object x). Also tried handling it as HttpRequest object as I've seen on some postings, to no avail. Not concerned about IE 9 incompatibility in this case; just want to see single file upload or at least a FormData object with key/value pairs properly received by an asmx WebMethod.
I did get it to work with the following code, in case anyone wants to see it:
var upload_file = $('#ipt_file')[0].files[0];
var upload_filename = upload_file.name;
var upload_maxsize = 10485760;
var upload_projectname = "test";
var form_data = new FormData();
form_data.append('session_id', this.sessionID());
form_data.append('project_name', upload_projectname);
form_data.append('file_name', upload_filename);
form_data.append('file_size', upload_file.size);
form_data.append('file', upload_file);
if (upload_file.size < upload_maxsize) {
var xhr_upload = $.ajax({
type: "POST",
headers: { 'Cache-Control': 'no-cache' },
url: "../services/upload.ashx",
data: form_data,
processData: false,
contentType: false,
dataType: "json"
}
})
.done(function (xhr_data) {
...
})
.fail(function (jqXHR, textStatus, errorThrown) {
...
})
.always(function () {
...
});
.NET will not allow the multipart/form-data for the content-type:
JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks
There is a built-in validation layer of protection that ASP.NET
enforces for both GET and POST based ASP.NET AJAX web methods, which
is that regardless of the HTTP verb being used, ASP.NET always
requires that the HTTP Content-Type header is set to the value
application/json. It this content type header is not sent, ASP.NET
AJAX will reject the request on the server.

Cast jsondata to NameValueCollection

I trying to pass JSON from jQuery to .ASHX file.
I want retrieve JSON data in .ASHX file by HttpContext and cats to NameValueCollection.
How do it?
$.ajax({
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
type: "Get",
datatype: "json",
onSuccess: function (data) {
}
});
Now I can use the querystring and And cast as follows:
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
string cururl = context.Request.Url.ToString();
int iqs = context.Request.Url.ToString().IndexOf('?');
string querystring = (iqs < cururl.Length - 1) ? cururl.Substring(iqs + 1) : String.Empty;
NameValueCollection parameters = HttpUtility.ParseQueryString(querystring);
context.Response.ContentType = "text/plain";
}
I want use json insted of querystring
Try this:
$.map(data.d, function (item) {
return {
name: item.Name,
family: item.Family
};
})
Or if you want each function:
var resultData = data.d;
$.each(resultData, function() {
alert(this)
})
I have made some changes hope this will help you :)
Ajax function
$.ajax({
type: "POST",
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if( data != null){
if (data.msg == "SUCCESS"); {
alert( data.msg)
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
.ASHX file
public void ProcessRequest(HttpContext context)
{
string outputToReturn = String.Empty; // Set it to Empty Instead of ""
context.Response.ContentType = "text/json";
var getName = String.Empty ;
var getFamily = String.Empty ; // Make sure if the Particular Object is Empty or not
if (!string.IsNullOrEmpty(context.Request["Name"]))
{
getName = context.Request["Name"];
}
if (!string.IsNullOrEmpty(context.Request["Subject"]))
{
getFamily = context.Request["Subject"];
}
NameValueCollection nvc = new NameValueCollection();
nvc.Add(getName, getFamily);
var dict = new Dictionary<string, string>();
foreach (string key in nvc.Keys)
{
dict.Add(key, nvc[key]);
}
string json = new JavaScriptSerializer().Serialize(dict);
Console.WriteLine(json);
}

Resources