How can i send a large array to MVC Controller - javascript

I am getting an error when sending an array with a length greater than 250 to MVC controller. It works when array length is less than 250 items.
Client Code
function saveVD() {
var arr = [];
$.each($("#tablevd tbody tr"), function () {
arr.push({
invNo: $(this).find('td:eq(0)').html().trim(),
invDate: $(this).find('td:eq(1)').html().trim()
})
})
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: "#Url.Action("Absorb","My")",
data: JSON.stringify({ 'arr': arr }),
success: function (result) {
},
error: function () {
}
})
}
Server Code
public class MyController : Controller
{
[HttpPost]
public JsonResult Absorb(CIVM[] arr)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
public class CIVM
{
public string invNo { get; set; }
public DateTime invDate { get; set; }
}

Below config changes may help you
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>

Related

How to Pass Jsonstringfy object with other parameters

I want pass more parameter with json stringify() but when passing other variable getting null value. please let me know right way of passing more variable .
I have tried this
data: {model:JSON.stringify(arr), buildingid ,shopid,post},
$("#btnArchive").click(function () {
var Buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
var Post = $("#SelectedValue").val();
var arr = [];
debugger;
//Loop through the Table rows and build a JSON array.
var customers = new Array();
$(".tblSavingCollChk:checked").each(function () {
var row = $(this).attr("chkid");
alert(row);
debugger;
//customers.push(row);
arr.push({ Id: row });
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Archive/UpdateStatus",
data: JSON.stringify(arr),
dataType: "json",
success: function (r) {
if (r == true) {
alert("Record Updated successfully");
document.location = '#Url.Action("ArchiveList","Archive")';
}
},
error: function (err) {},
});
});
Controller action
public ActionResult UpdateStatus([FromBody] ArchiveViewModel[] model,string buildingid, string shopid, string Post)//List values)
{}
If you want to pass more variable,I have a work demo like below, you can refer to it:
remove [Frombody] and dataType,contentType
In the controller:
public class jsonPostController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult GetData(Author jsonInput ,string cc, string buildingid, string shopid)
{
return View();
}
}
Index view:
<input type="button" id="btnGet" value="submit" />
<input id="BuildingId" value="aa" type="hidden" />
<input id="ShopId" value="aaa" type="hidden" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function () {
$("#btnGet").click(function ()
{
// Initialization
var jsonInput = {Id: 23, Name: "John" };
var buildingid = $("#BuildingId").val();
var shopid = $("#ShopId").val();
$.ajax(
{
type: 'POST',
url: '/jsonPost/GetData',
data: {
jsonInput: jsonInput,
cc: "cc", buildingid: buildingid, shopid: shopid
},
});
});
});
</script>
Author:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
}
result:

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"
});

Passing Multiple JSON objects via AJAX to ASP.Net PageMethod

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 "";
}

Unable to convert Javascript object to Java Model

My Spring controller and client side Javascript code are as follows and for some reason the Javascript object is unable to reach the Spring controller in the Object form. My Controller code is as follows:
#RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(#ModelAttribute("employeeRating") EmployeeRating employeeRating) {
if(employeeRating.getId()==0)
{
employeeRatingService.addRating(employeeRating);
}
else
{
employeeRatingService.updateRating(employeeRating);
}
return employeeRating;
}
My Javascript code below:
$.ajax({
url: 'https://myrestURL/addRating',
type: 'POST',
dataType: 'json',
data: {
'id':5,
'name': 'Name',
'rating': '1'
},
contentType: 'application/json; charset=utf-8',
success: function (result) {
// CallBack(result);
window.alert("Result: " + result);
},
error: function (error) {
window.alert("Error: " + error);
}
});
The EmployeeRating object in Java has id, name and rating fields so there's no mismatch.
Updating the model class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/*
* This is our model class and it corresponds to Country table in database
*/
#Entity
#Table(name="EMPLOYEERATING")
public class EmployeeRating {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#Column(name="name")
String name;
#Column(name="rating")
long rating;
public EmployeeRating() {
super();
}
public EmployeeRating(int i, String name,long rating) {
super();
this.id = i;
this.name = name;
this.rating=rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getRating() {
return rating;
}
public void setRating(long rating) {
this.rating = rating;
}
}
contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
$.ajax({
url: 'https://myrestURL/addRating',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
'id':5,
'name': 'Name',
'rating': '1'
}),
contentType: 'application/json; charset=utf-8',
success: function (result) {
// CallBack(result);
window.alert("Result: " + result);
},
error: function (error) {
window.alert("Error: " + error);
}
});

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");
}
});

Categories