Different way in constructing ajax data parameter? - javascript

I was quite confused with constructing data parameter of ajax using ASP.NET MVC and Webform and need an explanation from stackoverflow community.
First scenario (passing javascript object literal as data parameter in ajax using MVC) Results: It worked
MVC Controller
[HttpPost]
public JsonResult Register(string Name, string Birthday, int Gender)
{
.
.
.
return Json(message);
}
Javascript Code:
$.ajax({
url: "/Test/Register",
method: "POST",
dataType: "json",
data: {
Name:name,
Birthday:birthday,
Gender:gender
}
}).success(function (response) {
alert(response);
}).error(function (response) {
alert(response);
});
Second scenario (passing javascript object literal as a string as data parameter in ajax using MVC) Results: Cause error 500 (Internal Server Error)
Javascript Code:
var name = $('#Name').val();
var birthday = $('#Birthday').val();
var gender = $('#Gender').val();
var data = "{ Name:'" + name + "', Birthday:'" + birthday + "', Gender:'" + gender + "'}";
$.ajax({
url: "/Test/Register",
method: "POST",
dataType: "json",
data: data,
}).success(function (response) {
alert(response);
}).error(function (response) {
alert(response);
});
Results were different when I tested it on ASP.NET Webforms
Third scenario (passing javascript object literal as a string as data parameter in ajax using Webforms) Results: It worked
Webform WebMethod
[WebMethod]
public static string Submit(string Name, String Salary)
{
return "Success";
}
Javascript Code:
var name = $("#Name").val();
var salary = $("#Salary").val();
var data = "{ Name:'" + name + "', Salary:'" + salary + "'}";
$.ajax({
url: '/WebForm3.aspx/Submit',
contentType: "application/json; charset=utf-8",
method: 'POST',
data: data,
dataType: 'json',
success: function (response)
{
console.log(response);
},
error: function (response)
{
console.log(response);
}
});
Forth scenario (passing javascript object literal as data parameter in ajax using Webforms) Results: Cause error 500 (Internal Server Error)
$.ajax({
url: '/WebForm3.aspx/Submit',
contentType: "application/json; charset=utf-8",
method: 'POST',
data: {
Name: name,
Salary: salary
},
dataType: 'json',
success: function (response)
{
console.log(response);
},
error: function (response)
{
console.log(response);
}
});
Questions:
Why?
Will the scenarios that worked here on jQuery's ajax also work on other javascript frameworks like angularJS's $http service?
I also saw some scenarios on the internet that constructs its ajax data parameter using '=' example:
var reservation = { "CourseCode": courseCode.val().toString(), "Section": section.val().toString(), "DateFrom": dateF.toString(), "DateTo": dateT.toString(), "Schedule": reservations };
$.ajax({
url: '/ReserveSubject',
type: 'POST',
data: 'reservation=' + JSON.stringify(reservation),//Like this
Can anyone show more more ways to construct ajax data parameters aside from the scenarios above? It would also be much appreciated if someone could also show the most eloquent way of constructing data parameter.
No takers?

http://api.jquery.com/jquery.ajax/
documentation on jQuery's ajax data exerpts this:
data Type: PlainObject or String or Array Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
so you can pass it, string, aray or plain object,, while in Angulars data you can pass only string|object
https://docs.angularjs.org/api/ng/service/$http
so that's not same as in your examples,, you'll have to adjust if you send arrays

I suggest reducing the number of parameters on your controller actions to a single model object like:
public class RegisterModel
{
public string Name {get; set;}
public string Birthday {get; set;}
public int Gender {get; set;}
}
This is just good practice for clean code anyway.
And then in the client side you can have model builders which take the data you want to send and then send up this object instead of a bunch of parameters

Related

how to pass java script values to controller using post method in .net core application?

I am developing .net core application.i need to pass java script values to my controller using Post method. i am using java script code is below
data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (data) {
alert(data);
console.log('sample');
},
error: function(){
}
});
my controller is
[HttpPost]public string UploadData([FromBody] string imageValue)
{return imageValue;} but imageValue always it return null.if any mistake in my code please solve the problem.
When you make the ajax call, you should stringify the javascript object and send it. You can use the JSON.stringify method to convert the js object to it's JSON string equivalent.
var data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (data) {
console.log('sample', data);
},
error: function(){
}
});
Now since the ajax call is sending the data in the request body (since it is a POST request),You need to decorate the HttpPost action method parameter with [FromBody] attribute so that model binder knows it should read the data from the request body and map to the method parameter(YourViewModel) object.
public IActionResult UploadData([FromBody] YourViewModel d)
{
return Json(d);
}

How to use a var in ajax url with action razor syntax

I have a function that calls a method in controller through an Action URL, but I need use a parameter like name of Method, but this is not possible in this way.
function changeDropDownList(id, dropNameToChange, actionName, descriptionName) {
var control = $('#'+dropNameToChange);
control.prop("disabled", false);
$.ajax({
//Here I need use the actionName var, but only accept a string
url: '#Url.Action(actionName, "ThirdPartiesDef")',
dataType: "JSON",
data: { id: id },
contentType: "application/json; charset=utf-8",
success: function (result) {
control.empty();
$.each(result, function (index, item) {
control.append(
$('<option/>', {
value: item.Id,
text: item[descriptionName]
})
);
});
},
error: function (error) {
alert("Error: " + error);
}
});
}
I don't know so much of ajax and if you can say me some more easy method, it's ok.
Thank you for your help
You could use a placeholder inside the Url.Action server side Razor function that will be replaced by your javascript actionName variable on the client side:
url: '#Url.Action("#THE-ACTION#", "ThirdPartiesDef")'.replace('#THE-ACTION#', actionName)
which basically will emit the following markup inside the browser on the client:
url: '/#THE-ACTION#/ThirdPartiesDef/'.replace('#THE-ACTION#', actionName)
which after calling the changeDropDownList javascript function on the client it will replace the placeholder with the actionName javascript variable and you will end up with the correct url to use for your AJAX call.
As a side note you should remove the contentType: "application/json; charset=utf-8" parameter from your AJAX call because you are not sending any JSON at all in your data parameter.
You have to use JSON.stringify() method.
JSON.stringify() method turns a javascript object to json text and stores it in a string.
You specified contentType: "application/json; charset=utf-8", and the server waits to receive data in json format.
Also, you used wrong #Url.Action : #Url.Action(actionName, "ThirdPartiesDef")',.
One solution is to use .replace function:
'#Url.Action("myAction", "ThirdPartiesDef")'.replace('myAction', actionName).
In Razor every content using a # block is automatically HTML encoded by Razor.

Passing multiple parameters in ajax call

I am having having problem with sending the an object and two parameter in an ajax call.
My Server side method:
public ActionResult AddUpdate(string model, bool IsEdit, string Type)
{
//Do something
}
Client side ajax call is:
I am fetching all form values provided by user and saving them into "MemberObj" and sending another 2 parameters ie IsEdit and Type. but at server side i am getting only the IsEdit and Type values model parameter is null. The date value in ajax call after stringify is like:
"{"model":{"id":"123","Name":"Jhon Doe","Relation":"Father","Dob":"15-3-2014","Address":"abc":" abc","City":"abc","MobileNumber":"1234567890"},"IsEdit":false,"Type":"FamilyMember"}"
var MemberObj={};
MemberObj.Name="aaa";
var requestJSONData={ "model": MemberObj, "IsEdit": IsEdit, "Type": str[0] }
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: '/Employee/AddUpdate',
data: JSON.stringify(requestJSONData)
success: function (msg) {
//Success
},
error: function (msg) {
}
});
Any help is most appericiate.
Thanks
in one of my projects i used the following line and it works like a charm:
data: "{'sid':'" + sid.toString() + "'}",
try adapting yours to this format, it should work.

ajax client-to-server side

part a) I m trying to send the value stored in the variable 'mem_ID' from my javascript page...default.aspx to my server side - default.aspx.cs page. But I keep getting an error message.
$.ajax({
type: "POST",
url: "default.aspx.cs",
data: "{mem_ID : ' " + mem_ID + "'}",
async: true,
// success: function (result) { }
});
$ - is undefined.
Expected identifier or string.
part b) Also once i send this to the server side, how do i receive the value stored in the mem_ID ??
You could use a PageMethod. Let's take an example of such a method in your code behind:
[WebMethod]
public static string MyMethod(string memId)
{
return string.Format("Thanks for calling me with id: " + memId);
}
Things to note: the method must be static and decorated with the [WebMethod] attribute.
And on the client side you could invoke this method using the jQuery.ajax() function like this:
$.ajax({
url: 'default.aspx/MyMethod',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ memID : mem_ID }),
success: function (result) {
alert(result.d);
}
});
Also the error you are getting about the undefined $ symbol is related to the fact that you didn't reference the jQuery library in your page. So make sure that in your WebForm you have actually added reference to the jQuery library before using it. For example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>

$.ajax - send object for data property

I'm trying to call an asmx web service method with jQuery and pass an actual JavaScript object for the data, and get JSON back. The closest I can come is this:
$.ajax({
url: "WebService.asmx/HelloWorld",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ num: 12, name: "Adam" }),
dataType: "json",
success: function (data) { alert(data.d); }
});
How can I successfully make this call without first stringifying my object?
I tried this (removing the contentType)
$.ajax({
url: "WebService.asmx/HelloWorld",
type: "POST",
data: { num: 12, name: "Adam" },
dataType: "json",
success: function (data) { alert(data.d); }
});
But that returns the result in XML, not json.
Here's the web method:
[WebMethod]
[ScriptMethod]
public string HelloWorld(int num, string name) {
return ++num + name;
}
EDIT
Here's a screenshot of the headers of the request. Clearly content-type is set to xml for the response.
Set the ResponseFormat:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld(int num, string name) {
return ++num + name;
}
Just a NOTE: asmx doesn't return JSON for GETs only POST
Per Dave's Comments
It is impossible with the ASMX and ASPX JSON endpoints. They require the application/json Content-Type and a POST request or no JSON.

Categories