jQuery Ajax - deserialize object to xml - javascript

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?

Related

AJAX Call to Update table goes Null - ASP.NET

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.

AJAX Response Text Is Always Empty

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

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

Javascript Deserialize is returning the class name instead of actual object

So I'm running GetServerUpdateProgress() in the controller from a $.ajax call on my page. While debugging I can confirm that the variable: myobj is being properly created and filled with the correct data.
But when on the $.ajax success, I'm not getting the data in json format, instead I'm getting
a string of "TrackerMVC.ClassLib.UpdateAJAXProgress" - the objects type.
I've done this in the past with a .svc webservice and didn't have any problems getting the object values using this exact same method.
Any ideas? Thanks!
method:
public UpdateAJAXProgress GetServerUpdateProgress()
{
string BASE_URL = "http://localhost:55094";
string url = BASE_URL + "/Home/UpdateProgress";
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultNetworkCredentials; // uses current windows user
var myojb = new UpdateAJAXProgress();
var response = (HttpWebResponse)wr.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (UpdateAJAXProgress)js.Deserialize(objText, typeof(UpdateAJAXProgress));
return myojb; // during debugging this object has the correct values in the correct format
}
class:
public class UpdateAJAXProgress
{
public int Completed { get; set; }
public int Total { get; set; }
}
javascript:
$.ajax({
type: "POST",
async: false,
url: '#(Url.Action("GetServerUpdateProgress","Charts"))',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data); // data being returned is: "TrackerMVC.ClassLib.UpdateAJAXProgress"
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
You're misusing MVC.
You should declare your function as returning ActionResult, then return Json(myobj).
If you return a non-ActionResult from an MVC action, MVC will convert it to a string by calling ToString().

POST json object array to IHttpHandler

Im constructing an array of objects like this:
var postData = [];
$.each(selectedFields, function (index, value) {
var testTitle = 'testing ' + index;
postData.push({title: testTitle, title2 : testTitle});
}
I then post it like this(note that i have tried a number of different aproaches):
$.post('SaveTitlesHandler.ashx', { form : postData }, function (data) {
console.log(data);
});
I then try to get the data in a handler...
public class SaveTitlesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string json = context.Request.Form.ToString();
}
}
I cant seem to get proper json out of the request. Anyone got any idea?
cheers.
twD
You are not posting JSON. You are using application/x-www-form-urlencoded. So inside the handler you could access individual values:
public void ProcessRequest(HttpContext context)
{
var title1 = context.Request["form[0][title]"];
var title2 = context.Request["form[0][title2]"];
var title3 = context.Request["form[1][title]"];
var title4 = context.Request["form[1][title2]"];
...
}
If you wanted to POST real JSON you need this:
$.ajax({
url: 'SaveTitlesHandler.ashx',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(postData),
success: function(result) {
console.log(result);
}
});
and then inside the handler read from the request input stream:
public void ProcessRequest(HttpContext context)
{
using (var reader = new StreamReader(context.Request.InputStream))
{
string json = reader.ReadToEnd();
}
}
The JSON.stringify method converts a javascript object into a JSON string and it is a native method built-in modern browsers. You might also need to include json2.js if you want to support older browsers.

Categories

Resources