Passing Multiple JSON objects via AJAX to ASP.Net PageMethod - javascript

I am trying to pass two JSON Objects to my Page Method via AJAX
I created a class in Code Behind and created a JSON Object Array in javascript.
Following are my two classes and Page Method
public class userModel
{
public string userid { get; set; }
public string Name { get; set; }
}
public class companyModel
{
public string companyid { get; set; }
public string Name { get; set; }
}
[WebMethod]
public static string TestJsonMethod(userModel[] users)
{
return "";
}
And Following is my Javascript
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: []};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company = {companyid: "4", Name:"TEST COMPANY"};
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
Up till this point my code is working fine.
What I want to do is to pass the company object to the Page Method as well like this
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}

You could merge the models into one model.
public class TestJsonModel
{
public UserModel UserModel { get; set; }
public CompanyModel CompanyModel { get; set; }
}
Then action looks like;
[WebMethod]
public static string TestJsonMethod(TestJsonModel model)
Also, Ajax request post data looks like;
data: JSON.stringify({UserModel:obj,CompanyModel:company})

I was trying out different ways of doing it and this one worked.
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: [], company: {}};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company_ = {companyid: "4", Name:"TEST COMPANY"};
obj.company = company_;
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
And the Code behind Page Method remains same.
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}

Related

Sending data with post ajax to asp.net MVC controller

I am tried sent a data from view with ajax (POST) to controller in JSON format. From console.log, data is correct but data in controller missing...
Here is controller:
[HttpPost]
public ActionResult SavePermission(TestData testData)
{
return Json("DONE");
}
Here is model:
namespace INTRANETv4.Models
{
public class TestData
{
public string id { get; set; }
public bool read { get; set; }
public bool write { get; set; }
public bool delete { get; set; }
}
}
Here is javascript function from View:
function Save() {
var rows = document.getElementById("userTable").getElementsByTagName("tr");
var output = [];
for (i = 1; i < rows.length; i++) {
output.push({
id: rows[i].id,
read: rows[i].getElementsByTagName("td")[2].getElementsByTagName("input")[0].checked,
write: rows[i].getElementsByTagName("td")[3].getElementsByTagName("input")[0].checked,
delete: rows[i].getElementsByTagName("td")[4].getElementsByTagName("input")[0].checked
});
}
var myJSON = JSON.stringify(output);
console.log(myJSON);
$.ajax({
type: "POST",
contentType: "application/json",
data: myJSON,
url: "/Files/SavePermission",
dataType: "json"
});
}
Here is console.log of myJSON:
And here is content of testData from controller while debugging:
When i used string testData, because i worried about to convert, string was null. Thank you for any advice.
try
you model change to List<TestData> testData
and data change to JSON.stringify({ testData: output }),
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify({ testData: output }),
url: "/Files/SavePermission",
dataType: "json"
});

My insert method isn't working

I'm using dapper to map my database with my mvc project, i have debugged my code to know what's going on and my ReceiveData method isn't receiving the data for some reason when it sends it to my GeoCreate it shows nothing, also i might me wrong because i placed my cursor on my Geo.RouteID, Geo.Latitude,etc and the data was there then it goes to my geography class and after that it's supposed to go to the if statement but it stops there, i'm sending json data with postman.
Here's my ReceiveData method
public bool ReceiveData(Geography Geo)
{
int GeoCreate = this.conn.Execute(#"INSERT GEOGRAPHY([ID_ROUTE],[LAT],[LONG],[BATTERY],[DateCreated],[DEVICE_ID]) values (#Lat,#Long,#Battery,#DateCreated,#Device_ID)",
new { RouteID = Geo.RouteID, Lat = Geo.Latitude, Long = Geo.Longitude, Battery = Geo.Battery, DateCreated = Geo.ObtainedDate, DeviceID = Geo.Device_ID });
if(GeoCreate > 0)
{
return true;
}
return false;
}
Here's the action for calling the ReceiveData method:
[Route("GeoCreate")]
[HttpPost]
public bool StoreLocation(Geography Geo)
{
return GD.ReceiveData(Geo);
}
Here's the javascript code that works for sending my data:
<script>
$(document).ready(function () {
var Geograph = {
Latitude: $("#Latitude").val(),
Longitude: $("#Longitude").val(),
Country: $("#Country").val(),
ObtainedDate: $("#ObtainedDate").val()
};
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.parse( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});
});
</script>
And my Geography class:
public class Geography
{
[Key]
public int RouteID { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public int Battery { get; set; }
public DateTime ObtainedDate { get; set; }
public int Device_ID { get; set; }
}
Here's the JSON data i'm sending:
{
"Latitude": 19.435547,
"Longitude": -81.77856,
"Battery": 100,
"ObtainedDate":"\/Date(1522600449000)\/",
"Device_ID": 1
}
I'm not setting the RouteID because it fills automatically in the database.
In your ajax call you should use JSON.stringify rather than parse method
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.stringify( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});

MVC Controller and data received

I am trying to send json to my mvc action controller, I searched and researched on the web, but I always receive the object in my controller with all "null" fieds.
I tryed to send a string instead then an object but same result, a null string.
I really don't know what could be wrong:
Class:
namespace TestUser.Models
{
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Sex { get; set; }
public string Transfer { get; set; }
public string PercTransf { get; set; }
}
}
Controller:
[HttpPost]
public ActionResult CheckUser( User dati)
{
if (dati != null)
{
if (string.IsNullOrEmpty(dati.Name))
return Json("Insert the name");
if (string.IsNullOrEmpty(dati.Surname))
return Json("Insert the surname");
if (dati.Sex != "m" && dati.Sex != "f")
return Json("Insert the sex");
return Json("OK");
}
else
{
return Json("No valid data");
}
}
Ajax:
function checkAndSaveData() {
var obj = new Object();
obj.Name = $("#nome").val();
obj.Surname = $("#cognome").val();
obj.Email = $("#email").val();
obj.Sex = $('#selectSesso').find(":selected").val();
obj.Transfer = "no";
obj.PercTransf = "0";
if ($('#trasferte:checked').val() == "on") {
obj.Transfer = "si";
obj.PercTransf = $("#tempotrasf").val();
};
$.ajax({
type: 'post',
dataType: 'json',
url: '#Url.Action("CheckUser")',
data: JSON.stringify({ obj }),
success: function (json) {
if (json == "ok") {
$.ajax({
type: 'post',
dataType: 'json',
url: "#Url.Action("Save")",
success: function (json) {
if (json == "ok") {
alert();
} else {
alert(json);
}
},
});
} else {
alert(json);
}
},
});
}
You don't seem to be sending the dataObject object in the ajax request.
Try:
data: { JSON.stringify(obj) }
Also, the object you pass in the data field of the ajax request doesn't need to be on a 'dati' property of an object.
MVC should figure out the rest!
I always use fiddler for debugging issues like this to check the json your sending in the http request is as you'd imagine :)
your class properties and javascript properties should be same, then your controller action parameter name should match with jason string. so use like this JSON.stringify({"dati": obj });
There were many edits in the question so I'm going to publish full code. This worked for me when testing.
Javascript code
var obj = new Object();
obj.name = "name";
obj.surname = "cognome";
obj.email = "email";
obj.sex = 'm';
obj.transfer = "no";
obj.perctrasf = "0";
$.ajax({
type: 'post',
contentType: 'application/json',
dataType: 'json',
url: '#Url.Action("CheckUser")',
data: JSON.stringify({ dati: obj }),
success: function (json) {
if (json == "ok") {
alert("ok");
} else {
alert(json);
}
},
});
Controller
[HttpPost]
public ActionResult CheckUser(User dati)
{
return Json(dati);
}
Model
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Sex { get; set; }
public string Transfer { get; set; }
public string PercTransf { get; set; }
}

How to create a nested ajax requests?

I have a WEB API that is working fine. I want to call an action that is a part of my API via Ajax request. It seems that it is easy and I had it working for simple requests. However, I tried to put nested calls and for some reason the data that is passed to the second request gets lost. I was wondering if it is a scope problem or something I did wrong in my code.
Here is the javascript code:
$("#submit_request").click(function () {
var firstName = $("#first_name").val();
var lastName = $("#last_name").val();
var faciltiy = $("#facility").val();
// Collecting all the documents into an array of JSON
var documents = [];
var request = JSON.stringify({
"PatientFirstName": firstName,
"PatientLastName": lastName,
"Facility": faciltiy
});
//the first request is working fine and it has a success state
$.ajax({
url: "http://localhost:64611/api/requests/createRequest",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: request,
success: function (request_id, state) {
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
console.log(documents); // it is returning a correct object
console.log(typeof (documents)); // type object
$.ajax({
url: "http://localhost:64611/api/requests/addDocumentsOfARequest/",
type: "post",
datatype: 'json',
contenttype: 'application/json',
data: JSON.stringify(documents), ---> this object should be passed to the api action
success: function (response, state) {
},
error: function (err) {
if (err) {
}
}
});
},
error: function (err) {
if (err) {
}
}
});
});
The definition of my api action is like the following
public async Task<IHttpActionResult> addDocumentsOfARequest(RequestDocument[] documents)
The class RequestDocument is like the following:
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
My WebApiConfig is like the following:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "defaultApiRoutes",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"\d+" } // Only matches if "id" is one or more digits.
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
the parameter 'documents' is empty. Any idea?
Thanks!
Here's my exact working code :
Server
public class GamesController : ApiController
{
// GET api/<controller>
[HttpPost]
public async Task<IHttpActionResult> Post(RequestDocument[] document)
{
var req = await Request.Content.ReadAsStringAsync();
return Ok();
}
}
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
JavaScript
var documents = [];
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(documents),
success: function(a, b) {
alert("Done");
}
});
Result
try this,
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: {
document: documents
},
success: function(a, b) {
alert("Done");
}
});

Javascript send list to asmx service

I create an asmx service in .net web forms as below. The AddUsers method accept List model.
namespace ProjectName.AsmxServices.Test
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Test: System.Web.Services.WebService
{
[WebMethod]
public void AddUsers(List<UserDetail> userList)
{
// Add User List
}
// Here is my model
public class UserDetail
{
public int Id{ get; set; }
public string Name { get; set; }
public string Surname{ get; set; }
public DateTime BirthDate { get; set; }
}
}
}
Now, I want to post List model in Javascript. But how can I create this model as list in javascript ?
$("#addUsers").click(function () {
var data = ?? **How can I create a List<UserDetail> model.**
$.ajax({
url: '../AsmxServices/Test.asmx/AddUsers',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data
success: function (result) {
console.log("Good job!");
},
error: function (result) {
console.log("Failed");
}
});
});
I want to create this modelList hardcoded now. Then I will change my code.
Try this:
var usersList =
{
userList:
[
{Id: 1, Name: "name1"},
{Id: 2, Name: "name2"}
]
};
var data = JSON.stringify(usersList);

Categories