passing multiple parameters to .asmx from jquery ajax GET - c#

html
<a onclick="testGetParametersDynamic2();">fill in names and check it out</a>
<br />
<p>Enter First Name</p>
<input id="myFirstName" type="text" />
<br />
<p>Enter Last Name</p>
<input id="myLastName" type="text" />
<div id="outputGET3"></div>
c#
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true)]
public string testGetParametersDynamic(string firstName, string lastName)
{
string fullName = firstName + lastName;
return fullName;
}
I have tried multiple ways of entering data bc I think this is where the problem lies
attempt 1
function testGetParametersDynamic2()
{
$.ajax(
{
post: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":' +
$('#myLastName').val() + '"}',
url: 'UtilitieService.asmx/TestGetParametersDynamic',
success: function (result)
{
var test = result.d;
var outputDiv = $('outputGET3');
outputDiv.html(test);
},
error: function ()
{
alert('Fail Test Get Dynamic');
}
});
}
attempt 2:
function testGetParametersDynamic2()
{
$.ajax(
{
post: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: "firstName" + $('myFirstName').val() + "&lastName" + $('myLastName').val(),
url: 'UtilitieService.asmx/TestGetParametersDynamic',
success: function (result)
{
var test = result.d;
var outputDiv = $('outputGET3');
outputDiv.html(test);
},
error: function ()
{
alert('Fail Test Get Dynamic');
}
});
}
both times I get this error:
Invalid web service call, missing value for parameter: \u0027firstName\u0027

I hope that you use [ScriptMethod(ResponseFormat=ResponseFormat.Json)] attribute for the web method or set the same information in the web.config in case of the usage .NET 4.0.
It seems to me that your first attempt was almost correct, but you should replace
data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":' +
$('#myLastName').val() + '"}',
to the
data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":"' +
$('#myLastName').val() + '"}',
(the starting double-quote was skipped before the $('#myLastName').val()).
I strictly recommend you don't use manual serialization to JSON. For example if the text from $('#myFirstName').val() or $('#myLastName').val() will have '"' or '\' characters, that the characters must be escaped with additional backslash ('\') (see here). Instead of manual serialization you should use JSON.stringify function from the script json2.js which you can download from the http://www.json.org/js.html or here. In recent web browsers the function are native implemented and json2.js use the native implementation if it take place.
The data parameter of $.ajax could be rewritten as the following:
data: {
firstName: JSON.stringify($('myFirstName').val()),
lastName: JSON.stringify($('myLastName').val())
}
or in some situation even as
data: {
firstName: function() { return JSON.stringify($('myFirstName').val()); },
lastName: function() { return JSON.stringify($('myLastName').val()); }
}
For more information see this old answer and probably also this.
UPDATED: Sorry the correct version without the usage JSON.stringify could be without the data usage:
url: 'UtilitieService.asmx/TestGetParametersDynamic?firstName=' +
encodeURIComponent('"' + $('#myFirstName').val() + '"') +
'&lastName=' + encodeURIComponent('"' + $('#myLastName').val() + '"')
I strictly recommend you to use always only the JSON.stringify version which I described above.

Your first attempt is passing the paramaters as a json string.
Your second attempt is missing = signs.
You can pass a object to data, and jQuery will serialize it properly.
$.ajax(
{
post: 'GET',
data: {
firstName: $('myFirstName').val(),
lastName: $('myLastName').val()
},
...

Pass multiple parameters using json
data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value +
"'," + "'tempdata':'" +"myvalue" + "'}",

Related

MVC C# call non controller method (helper) from ajax. Possible or not?

I'm working on an MVC C# web that has a "shared" project which has a Helper class called ImageUrlHelper that has a method called GenerateAzureUrl which returns a string, and I need to call this method through an ajax call.
I've tried:
$.ajax({
type: 'POST',
url: '/Helpers/ImageUrlHelper/GenerateAzureUrl',
data: '{ "path": "' + path + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
}
});
But it's not working, and I'm guessing you can only call a controller method from Ajax. Am I right? Or maybe it should work and I'm doing something wrong in my call.
BTW, this is my Helper method:
public static string GenerateAzureUrl(string path)
{
var pathPartsFromI = Regex.Split(path, "/i/");
if (pathPartsFromI.Length != 2) return path;
var rightPathParts = Regex.Split(pathPartsFromI[1], "/");
if (rightPathParts.Length < 2) return path;
var id = rightPathParts[0];
var size = (rightPathParts.Length == 2 ? "ori" : rightPathParts[1]);
var slug = rightPathParts[rightPathParts.Length - 1];
var extension = slug.Split('.')[1].Split('%')[0];
string azureUrl = _urlAzureImageDomain + "/images/" + size.ToLower() + "/" + id + "." + extension;
bool imgExists = ImageExists(id, size.ToLower(), extension);
if (!imgExists)
{
if (size.ToLower() != "ori") imgExists = ImageExists(id, "ori", extension);
if (!imgExists) return "/Content/images/image_not_found.jpg";
azureUrl = _urlAzureImageDomain + "/images/ori/" + id + "." + extension;
}
return azureUrl;
}
What I'm receiving is a 404 Not Found.
Thanks.
As mentioned in the comments,
Create an action in a controller class that calls the GenerateAzureUrl() method.
[HttpPost]
[Route("get/azure/url/from/api/{path}")]
public string GetAzureUrlFromAPI(string path)
{
return GenerateAzureUrl(path);
}
In AJAX call:
$.ajax({
type: 'POST',
url: '../../../get/azure/url/from/api/' + path,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
}
});
You cannot use like that, as you already has answer with you "Controller". AJAX from Web browser take routing help to call the methods.
Check other reference: Ajax method call
Thanks

Apostrophe causes problems in AJAX method

I have a textbox (txtDescription) where the user can type a description when an event is canceled.
The problem is when the there is an apostrophe ' with in that textbox AJAX throws an error. Without the apostrophe it works and saves fine.
I have tried using JSON.stringify but this did not work.
This is my code:
$("#btnCancelEvent").click(function () {
var CencelDesc = $("#txtDescription").val();
var user = $("#lblFullName").html();
if (CencelDesc === "") {
alert("Please provide a reason why this schedule event is being canceled.");
return false;
} else {
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: "{'ScheduleID': '" + ScheduleID +
"','CentreID': '" + CentreID +
"','CencelDesc': '" + CencelDesc + //this is where the problem occurs
"','user': '" + user + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
return false;
}
return false;
});
Please assist how I can fix this issue.
Two issues:
JSON uses double quotes, not single quotes.
Never buld JSON strings by hand. Instead, build an object and let JSON.stringify handle the escaping, etc., for you.
So:
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: JSON.stringify({ScheduleID: ScheduleID
,CentreID: CentreID
,CencelDesc: CencelDesc
,user: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
Side note: There's no need for dataType: "json" in that code. You're not doing anything with the response. In fact, in general, using dataType is an anti-pattern. Instead, ensure that the server sends back the correct Content-Type header.

Passing string from AJAX to ASP.NET C# code behind

I am new to JS, even less experienced at AJAX. I'm just trying to pass a value to the code behind and return an expanded response.
The problem is that despite the call succeeding, the string value passed from AJAX to C# is never anything other than "undefined", and it is driving me insane.
The JS
function test() {
var message = "this is a test" ;
Display(message);}
function Display(words) {
var hummus = { 'pass': words};
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: hummus,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words + "\n\nError: " + lion);
}
});}
The Code Behind
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
string beans = pass + ". We repeat this is only a test.";
return beans;
}
The end result is invariably "Your fortune: undefined. We repeat this is only a test."
I would only like to know what I am missing.
Yes this is probably a stupid question but my searches reveal nothing helpful.
Your issue is that you are trying to accept a string in your method public static string ShowMe(string pass) but you are passing a JavaScript object as your data. See when you make an Ajax call ASP.Net will do its best to match up the data you posted to the type you have in your parameter - called Model Binding. When this cannot be achieved then you get an null passed in.
So in your JavaScript you are passing a JavaScript object using this:
var hummus = { 'pass': words};
$.ajax({
....,
....,
data: hummus,
If you wish to post an object then your controller/method needs to have a C# model (class) that your JS will be bound to.
So change your method to accept a model:
// somewhere in your code put this little model
// this is what your JavaScript object will get bound to when you post
public MyModel{
// this is to match the property name on your JavaScript object, its case sensitive i.e { 'pass': words};
public string pass {get;set;}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(MyModel model)
{
// you can now access the properties on your MyModel like this
string beans = model.pass + ". We repeat this is only a test.";
return beans;
}
I found two issues in your code -
Missing data: JSON.stringify(hummus),
Remove lion which variable doesn't exist.
Fix
function test() {
var message = "this is a test";
Display(message);
}
function Display(words) {
var hummus = { 'pass': words };
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: JSON.stringify(hummus), // Missing JSON.stringify
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// remove lion which variable doesn't exist.
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
}
});
}
Working code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Account.aspx.cs" Inherits="WebApplication1.Account" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button type="button" onclick="test()">Display Word</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
var message = "this is a test";
Display(message);
}
function Display(words) {
var hummus = { 'pass': words };
$.ajax({
type: 'POST',
url: 'Account.aspx/ShowMe',
data: JSON.stringify(hummus), // Missing JSON.stringify
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert("Your fortune: " + response.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// remove lion which variable doesn't exist.
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + words);
}
});
}
</script>
</form>
</body>
</html>
public partial class Account : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ShowMe(string pass)
{
string beans = pass + ". We repeat this is only a test.";
return beans;
}
}
Thank you both for your help. I'm going to try the Model method, the JSON.stringify was something I had tried before and ultimately worked.
Apparently the problem I was not understanding how my browser worked. No matter what changes I made I was getting the same error. The reason?
My code wasn't in tags on the page, it was in a separate js file which Chrome was caching for me, effectively negating every change I made to try and correct the problem and driving me insane in the process.
In all I've learned a new technique, Model Binding, and that location of code can dramatically effect your Javascript experience.

how to resolve ajax post jquery in asp.net page?

when i add alert(file) line after ajax block code work but when i remove alert(file) code not work .
this is work fine :
function Delete(file) {
$.ajax({
type: "POST",
url: "Image.aspx/Delete",
data: '{file: "' + file + '" }',
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$("#statusBox").text("ok"); //alert(response.d);
},
error: function (response) {
$("#statusBox").text("error"+response.text);
// alert(response.status + ' ' + response.statusText);
},
complete: function () {
// $("#statusBox").text("completed");
}
});
alert(file);
}
if i remove alert(file) line code web method not work.
this my c# asp.net code web method :
[WebMethod]
public static string Delete(string file)
{
try
{
// int lastSlash=file.ind
// Lesson learnt - always check for a valid URI
if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
{
Uri uri = new Uri(file);
file = (uri.LocalPath);
}
//file= file.Remove(0)
//File.Delete(file);
File.Delete(HttpContext.Current.Server.MapPath(#"~\" + file.Replace("/", #"\")));
}
catch (Exception ex)
{
return ex.Message;
}
return "ok";
}
You're sending the request asynchronously,try to make false asynchronous.
for more information take a look at this
I see three (3) errors in your code:
data: '{file: "' + file + '" }',
datatype: "jsondata",
async: "true",
You are not sending a js object to the server.
jsondata is not a valid datatype.
async is a boolean and you are instead assigning a string value.
So the solution from here is:
data: {file: file }, // send a object
datatype: "text", // change to text because you are returning "ok" string
async: true, // remove the quotes
Another suggestion is try with default headers:
contentType: "application/json; charset=utf-8",
Try removing this line and see.

jQuery AJAX call to an ASP.NET WebMethod

I have the following jQuery AJAX request:
function sendUpdate(urlToSend) {
var code = AccessCode;
var url = urlToSend;
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "webmethods.aspx/UpdatePage",
data: "{ accessCode: " + code + ", newURL: '" + url + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
And the corresponding ASP.NET WebMethod:
[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try
{
HttpContext.Current.Cache[accessCode + "l"] = newURL;
}
catch
{
result = false;
}
return result;
}
That all used to work correctly with "async:false", however I have to get rid of it as it freezes the browser until the response is received. Now the AJAX request above returns "undefined".
Could anybody tell me why it happens and where the problem is?
Thanks.
You should really make sure to properly encode this JSON. JSON.stringify is the most reliable method:
data: JSON.stringify({ accessCode: code, newURL: url })
This ensures that even if the code and url variables contain some dangerous characters that will break your string concatenations in the resulting JSON at the end everything will be properly encoded. The JSON.stringify method is natievly built into modern browsers but if you need to support legacy you could include json2.js.
Also because you code is no longer blocking you should make sure that if you call this sendUpdate from some button click or form submit you cancel the default action by returning false.
My way works correctly:
[System.Web.Services.WebMethod()]
public static string getHello(string str)
{
//do some things with str
return str;
}
In file .js, I define this function to call webmethod in file .cs:
function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json",
success: function (result) {
if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
CallBackFunction(result);
}
},
error: function (result) {
alert('error occured');
alert(result.responseText);
window.location.href = "FrmError.aspx?Exception=" + result.responseText;
},
async: true
});
}
Then, call to use (call in file.js):
var text = $("#textbox_send").val();
var myresult;
CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
if (text != "")
$('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
});
The "undefined" could be the result of a server error.If you use Firebug,Firefox(or any good client debugging tool), you can find the error returned by the server. Paste the error,if any.
Nevertheless, I also noted the the "data" for "accessCode" is not properly enclosed within quotes ‘ ’
The corrected data option would be :
data: "{ accessCode: '" + code + "', newURL: '" + url + "' }",
PS:
Since 'options' have a different meaning in Jquery, I would recommend changing the variable name as 'setting' . Change 'var options ' to 'var settings'. :)

Categories