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.
Related
I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
I want to pass a lot of parameters from my ajax function to my controller. Initially, I thought I would just do this using a query string but that wasn't giving me the result I wanted, although it worked it was creating an unattractive URL the more data I added.
I thought the better approach would be to take all this data I need to pass, store it as an object and pass that payload into the controller from an ajax function.
The ajax function is triggered from the .event() attribute of the KendoGrid.
Kendo Grid
#(Html.Kendo().Grid<MyProject.Models.Car>()
.Name("requirement-grid")
.Columns(columns =>
{
columns.Bound(c => c.Name);
columns.Command(command => command
.Custom("Test").Click("payload"));
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetCars", "cars"))))
As you can see from the above code, there is a custom command that I've used which triggers a function when you click on it. The function is payload and the code is as follows:
payload
function payload(e) {
e.preventDefault();
//Get row data
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Create Object
var obj = {
Name: dataItem.Name,
BHP: dataItem.BHP,
YearOfBuild: dataItem.YearOfBuild
}
//Post via Ajax
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
}
I access the data of the row that was clicked on and pass it down via the events parameter, from there I create an object and add the data to it. I then create an ajax call and try to pass it to the controllers.
The controller expects the parameter, the code is as follows but shortened for brevity.
Controller
public ActionResult Create(object[] obj)
{
return View(obj);
}
If I use "POST" in my ajax function I get an error regarding a anti-forgery token which is missing. If I use "GET" the obj parameter is always null.
The required anti-forgery cookie "__RequestVerificationToken" is not present.
Is there a better way to be doing this or is my approach incorrect?
So this should be a relatively simple change to your code. I am assuming you have an anti-forgery token loaded onto the page and the action you are posting to is protected by this. You have two solutions here:
1) Remove the requirement for the token if it isn't needed from the action in your controller
2) Provide the token as part of the data package you are sending back to the server by changing your code from
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
to:
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: {
array: JSON.stringify(obj),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log("Success");
},
error: function(ob, errStr) {
console.log(ob.responseText);
}
});
Notice I have just added a reference to the anti-forgery token as part of the data package for you and this should be read by the controller and allow the command to complete successfully for you if you have the token on the page. if not then just add the #Html.AntiForgeryToken() to the view and you should be fine.
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
I am trying to build an ASP.NET MVC web service in which I am trying to make a POST call in javascript using jQuery ajax as below.
$.ajax({
url: "/bug/CreateBug",
type: "POST",
data: rowData,
contentType: "application/json",
datatype: "json", //return type
success: function (data) {
console.log(data);
},
error: function (xhr) {
alert('error');
}
});
I keep getting the error TypeError: e is undefined. I tried adding a log statement just before this ajax call and things are working fine. Not sure what am I missing out on. My rowData looks something like below.
{
"Date": "2016-12-31",
"Id": "1234-csj4-sadf-random",
"Scenario": "abc",
"IsFixed": "No"
}
My C# code in the controller looks something like this
[HttpPost]
public JsonResult CreateBug(string jsonRequest)
{
var bugId = GetBugId(jsonRequest);
return this.Json(bugId, JsonRequestBehavior.AllowGet);
}
I tried to test the above POST call using Postman and I got jsonRequest as null. Could someone pls help me out here on how can I get the POST request to work?
Thanks in advance!
try it hope it works
$.ajax({
url: "/bug/CreateBug",
type: "POST",
data: JSON.stringify(rowdata),
contentType: "application/json",
datatype: "json", //return type
success: function (data) {
console.log(data);
},
error: function (xhr) {
alert('error');
}
});
------ on controller
do something like this or the best approach is to create model with all these property and MVC will bind it for you.
[HttpPost]
public JsonResult CreateBug(string Id, string Date, string IsFixed , string Scenario)
{
var bugId = GetBugId(jsonRequest);
return this.Json(bugId, JsonRequestBehavior.AllowGet);
}
Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});