I'm trying to update my table using Ajax Call through this code
var customer = {};
customer.CustomerId = row.find(".CustomerId").find("span").html();
customer.Nome = row.find(".Nome").find("span").html();
customer.Tipo = row.find(".Tipo").find("span").html();
customer.NCM = row.find(".NCM").find("span").html();
customer.Contabil = row.find(".Contabil").find("span").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
But when I click to update the value it returns a System.NullReferenceException, I can't see where I'm doing wrong.
Here's my Controller Code
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
entities.SaveChanges();
}
return new EmptyResult();
}
System.NullReferenceException revealed the value updatedCustomer or customer is null.You need check which is null.
And when you want to update a enity in EF,you need add code like :
context.Entry(existingBlog).State = EntityState.Modified;
Howerver,Why you need Query A Entity befor update?I guess you want to do this:
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
entities.Entry(customer).State = EntityState.Modified;
entities.SaveChanges();
}
return new EmptyResult();
}
This AJAX callback below actually passed JSON string containing JSON object, which is wrong and causing customer contains null value which throwing NullReferenceException (it is strongly advised to put null check before using EF entity context):
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}', // this is wrong
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Instead of passing JSON string like that, just use data: JSON.stringify(customer) or simply passing entire object directly with data: customer and remove contentType setting:
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: customer,
dataType: "json",
success: function (result) {
// do something
}
});
Regarding second issue which selected data from table query is not updated, it depends on auto-tracking setting from EF. If auto-tracking is disabled, you need to set EntityState.Modified before using SaveChanges():
if (customer != null)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
// if EF auto-tracking is disabled, this line is mandatory
entities.Entry(updatedCustomer).State = System.Data.Entity.EntityState.Modified;
entities.SaveChanges();
}
}
Notes:
1) You can see all methods to update existing data with EF in this reference.
2) This fiddle contains sample to make AJAX request from a table contents.
Related
The type of the object I want to handle in my controller is: List>. So basically, on the server side I have a method:
public void foo(List<Tuple<bool, string>> arg)
And on client side: I have an array of javascript objects that I fill up as shown below:
var _array = [];
for (var i = 1; i <= checkBoxesCount; ++i) {
var currentBool = $("input[id^='xx+" + i + "']").is(":checked");
var currentString = $("label[id^='yy+" + i + "']").attr('stringValue');
_array.push({
boolValue: currentBool,
stringValue: currentString
});
}
I have checked that the boolean and strings values are read correctly on client side.
The exact error I'm getting is An exception of type 'System.InvalidCastException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Impossible to cast a 'System.String' object into a 'System.Dynamic.ExpandoObject'. in the JsonNetValueProviderFactory.cs file
EDIT: Ajax call:
$.ajax({
url: myUrl,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'array': _array })
});
I'm using asp.net web forms and trying to call a web service method from a java script function using AJAX which returns a JSON array with a car number and a car number ID pairs
the web methods resides in the same code behind file of the java script function page
I checked the json variable more than one time using the debugger and made sure it holds a valid JSON array
however when I checked the cars object in the FillLimoCars java script function I found the response text to be an empty array
I'm not sure why this is happening I hope that anyone of you would be able to help
Java Script
function testButton(carModelID) {
$.ajax({
type: "POST",
url: baseURL + "WebPages/NewPages/ListCarRental.aspx/FillLimoCars",
data: "{CarModelID:'" + carModelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: FillLimoCar
});
}
function FillLimoCar(cars)
{
var rdd_LimoCars = $find("<%=rdd_LimoCarNumber.ClientID %>");
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
for(var i = 0; i < cars.length; i++)
{
;
}
}
C#
[WebMethod]
public static string FillLimoCars(int CarModelID)
{
try
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<LimoFleet> limos = carsBLL.GetCarModelLimoFleet(CarModelID);
List<object> objLimosList = new List<object>();
foreach(var limo in limos)
{
var limoObj = new
{
CarID = limo.CarID,
CarNumber = limo.CarNumber
};
objLimosList.Add(limoObj);
}
var json = serializer.Serialize(objLimosList);
return json;
//Context.Response.Write(objLimos.ToJson());
}
catch (Exception ex)
{
Tracer.Singleton.Log(ex);
return null;
}
}
You have to use success attribute. Inside success, you have to de serialize JSON object.
$.ajax({
type: "POST",
url: baseURL + "WebPages/NewPages/ListCarRental.aspx/FillLimoCars",
data: "{CarModelID:'" + carModelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
"success": function (json) {
if (json.d != null) {
FillLimoCars(json.d);
}
});
I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.
I have big array which exceed request object length so i am thinking to send data to controller in small data frames so that it will not get crashed on extending http request object limit and data will in after certain interval of time.....
var param = "&table=" + table; //remove first three charactor 'btn' from id
param = param + "&tblheader=" + tblheader;
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
dataType: 'text',
contentType: 'application/text; charset=utf-8'
});
controller :
[HttpPost]
public ActionResult SendReport(string table, string tblheader)
{
}
I Thinks your url isnt validate :
check this code please :
var param = { Table: table
Tblheader: tblheader }; //json data
var request = $.ajax({
url: '../Reports/SendReport'
data: param,
type: 'POST',
cache: false,
dataType: 'json',
contentType: 'application/text; charset=utf-8'
});
Create Json object and send using ajax
var ajaxPostDatastr = '{"table":"' + table + '","tblheader":"'+tblheader+'" }';
var jsonData = JSON.parse(ajaxPostDatastr);
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
contentType: 'application/text; charset=utf-8',
data: jsonData});
In controller use same as what you did right now.
Hope this will solve your issue
You can send large data via JSON. But you need to increase the maxlength of the json data in web.config.
Refer the post : Getting "The JSON request was too large to be deserialized"
All above way right to send data but when we are using
var param = "&table=" + table; //remove first three charactor 'btn' from id
param = param + "&tblheader=" + tblheader;
var request = $.ajax({
url: '../Reports/SendReport?'+param,//action method url which defined in controller
type: 'POST',
cache: false,
dataType: 'text',
contentType: 'application/text; charset=utf-8'
});
then we are passing data as a parameter to the $.ajax then it has a certain limit around param.length = 1600 then after $.ajax fail to execute
if you want to send huge data then you have to use View Model object and assign this values on data so it will work easily..
because as i m using Asp.net MVC ,in that view model is strongly bonded to view.so we can assign .if nay having better soln please share
I want to post data to my service and I have chosen XML instead of JSON because I have database logic that will query the xml.
So this is my code so far:
var saveChanges = function (agencyObservable) {
if (agencyObservable) {
var data = ko.toJS(agencyObservable._latestValue[0]);
var options = {
url: '/breeze/SaveData',
type: 'POST',
dataType: 'xml',
data: data,
contentType: "application/json; charset=utf-8"
}
}
Breeze.webapi
[HttpPost]
public void SaveData(XmlDocument xmldoc)
{
tblAgencyQuery tblAgencyQuery = new tblAgencyQuery();
tblAgencyQuery.QueryID = Guid.NewGuid();
//tblAgencyQuery.QueryText = data.ToString();
//tblAgencyQuery.AgencyID = DeserializedData.agencyID;
tblAgencyQuery.CreatedDate = DateTime.UtcNow;
_ContextProvider.Context.tblAgencyQuery.Add(tblAgencyQuery);
_ContextProvider.Context.Entry(tblAgencyQuery).State = System.Data.EntityState.Added;
_ContextProvider.Context.SaveChanges();
}
agencyObservable is knockout observable and I am converting it to a standard javaScript object. But I don't know what to do from here. I want to somehow change my object to XML but is this easy or possible?