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

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.

Related

How to get data through asp.net core api call using html and jquery?

I want to post data in the Mssql Database using Asp.netCore Api and Html Form. I have Added This script to post data.but All the values are coming null
Jquery script in Html File
<script type="text/javascript">
var valdata = $("#formData").serialize();
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
let formData = {};
$("#formData").serializeArray().map((x) => { formData[x.name] = x.value; });
$.ajax({
url: "https://localhost:44389/Register",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
.net Core Api
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromBody]CustmRegistration Register)
{
try
{
userInterface.InsertCustomer(Register);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
but All the values are coming null
Where are these values null? my suggestion is to start debugging a bit more thoroughly.
Have you tried your api function trough postman or a tool likewise?
Settting breakpoints can be nice to look into your program's data at runtime.
if these values are null in your database it would be nice to see what userInterface.InsertCustomer(Register); does.
Once you know if your .net part is working start debugging your ajaxc call. take a look at the network section of the developer tools form the browser you are using.
If you have collected more data, people can help you more easelly.
1.When you use .serialize(), it generates the data in a query string format which needs to be sent using the default contentType which is application/x-www-form-urlencoded; charset=UTF-8, not as JSON. Either remove the contentType option or specify contentType: application/x-www-form-urlencoded; charset=UTF-8 can work.
2.Also you need move the serialize method into onclick event.
3.Be sure change [FromBody] to [FromForm].
Here is a whole working demo:
View:
#model CustmRegistration
<form id="formData">
<!--more code-->
<input type="button" id="btnsubmit"value="create" />
</form>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
var valdata = $("#formData").serialize(); //move to here...
$.ajax({
url: "/home/Register",
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
}
Controller:
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromForm]CustmRegistration Register)
{ //...}

Calling a method with ajax in aspx.cs from aspx

I am trying to call a method from my aspx page. This method is found on the aspx.cs page, but it is throwing an error. Do you know what's wrong, please?
ajax script
<script type="text/javascript">
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
} //Default.aspx
function insertMarker() {
var usernameName = 'username';
var usernameVal = document.getElementById('<%=hdnUsername.ClientID%>').value;
var latitudeName = 'latitudeStr';
var latitudeVal = document.getElementById('<%=hdnMarkerLatitude.ClientID%>').value;
var longituteName = 'longitudeStr';
var longitudeVal = document.getElementById('<%=hdnMarkerLongitude.ClientID%>').value;
var iconName = 'markerIcon';
var iconVal;
if (document.getElementById('blueMarker').checked) {
iconVal = 'images/blueMarker.png';
}
if (document.getElementById('greenMarker').checked) {
iconVal = 'images/greenMarker.png'
}
if (document.getElementById('pinkMarker').checked) {
iconVal = 'images/pinkMarker.png';
}
var titleName = 'name';
var titleVal = document.getElementById('<%=title.ClientID%>').value;
var descriptionName = 'description';
var descriptionVal = document.getElementById('<%=description.ClientID%>').value;
$.ajax({
type: "POST",
url: "mapping.aspx/insertNewMarker",
data: {"username" : usernameVal, "longitudeStr":longitudeVal, "latitudeStr" :latitudeVal, "markerIcon":iconVal, "name" : titleVal, "description" :descriptionVal},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Website Design
Save Marker
Title
Description
Save
Aspx.cs Method.
[ScriptService]
public partial class mapping: System.Web.UI.Page
{
[WebMethod]
private static void insertNewMarker(string username, string longitudeStr, string latitudeStr, string markerIcon, string name, string description)
{
//My Code
}
}
Your server-side webmethod cannot be private, you have to change it to public.
From MSDN documentation on webmethods:
When you create a Web service in managed code, you indicate the
methods that are available through that Web service by placing the
WebMethod attribute before the method declaration of a Public method.
Private methods cannot serve as the entry point for a Web service
although they can be in the same class and the Web service code can
call them.
Change your data like this
data:JSON.stringify({username : usernameVal, longitudeStr:longitudeVal, latitudeStr :latitudeVal, markerIcon:iconVal, name : titleVal, description :descriptionVal}),
You need to pass data as json stirng which has a specific format. If you use JSON.stringify data will be convetred to json string and if you don't use this than you have to pass every paremter and its value in quotes like this.
data:"{username:'" + usernameVal + "',............}",

Can we call User control code behind method using Jquery ajax?

I'm trying to do something, Can we call User control code behind method using Jquery ajax ?
likes:
ASCX CODE:
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Uploads.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
ASCX.CS
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
But its will create an error please can any one what do i am wrong.
The user control doesn't have all the functionality of a page and can't be called directly.Check out the following link for complete solution
Creating a Page method (ScriptMethod) within an ASCX user control using AJAX, JSON, base classes and reflection

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'. :)

passing multiple parameters to .asmx from jquery ajax GET

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" + "'}",

Categories