I have ran into a predicament. I am passing data to the controller using ajax, and the controller has a method that passes the data to the DAL and the DAL returns an int, that is the newly created ID of the inserted record. My question is how do I get the returned ID and then place it into LocalStorage?
Here is the NewVendorToSubmit
function NewVendorToSubmit() {
var isItChecked;
if ($("#sTaxEnabled").prop("checked")) {
isItChecked = "1";
}
else isItChecked = "0";
var Vendor = {
VendorName: $("#txtVendorName").val(),
Address1: $("#txtVendorAddress1").val(),
Address2: $("#txtVendorAddress2").val(),
City: $("#txtVendorCity").val(),
State: $("#acVendorState").val(),
Zip: $("#txtVendorZip").val(),
VendorPhone: $("#txtVendorPhone").val(),
VendorFax: $("#txtVendorFax").val(),
Email: $("#txtEmail1").val(),
Email2: $("#txtEmail2").val(),
TaxEnabled: isItChecked
};
return Vendor;
}
Here is my jquery function that gets called on the button save event
function SubmitNewVendor() {
var newVendor = NewVendorToSubmit();
$.ajax({
type: "POST",
url: URLParam.AddNewVendor,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newVendor),
success: function (data, textStatus, jqXHR) { },
complete: function (e) {
ClearVendorFields();
GetVendorGridData();
//CloseTheWindow();
}
})
}
Here is the Controller method that it is calling
[HttpPost]
public int AddVendor(NewVendorToAdd nvta)
{
DAL = new UsherDAL();
int addedVendorID = DAL.AddNewVendor(nvta);
return addedVendorID;
}
and here is the method that is being called from the DAL
public int AddNewVendor(NewVendorToAdd nvta)
{
Vendor vendor = new Vendor();
Address address = new Address();
VendorAddressXREF vendoraddressxref = new VendorAddressXREF();
vendor.VendorName = nvta.VendorName;
int newVendorID = InsertVendor(vendor);
address.Line1 = nvta.Address1;
address.Line2 = nvta.Address2;
address.City = nvta.City;
address.ZipCode = nvta.Zip;
address.StateID = nvta.State;
int newAddressID = InsertAddress(address);
vendoraddressxref.VendorID = newVendorID;
vendoraddressxref.AddressID = newAddressID;
int newVendorAddressXREFID = InsertVendorAddressXREF(vendoraddressxref);
return newVendorID;
}
So how do I go about getting the returned int from AddNewVendor and placing that into LocalStorage, without having to make another round trip to the database?
It seems that the vendor's ID is returned as a response to the POST request, to store it in the local storage you can do this:
$.ajax({
...,
success: function (data, textStatus, jqXHR) {
if(window.localStorage){
localStorage.vendorID = data;
}
},
...
})
Related
I have a model created in javascript as follows
function Vehicle() {
this.type = 'Vehicle';
this.data = {
VehicleKey: null
}
};
I have a similar model created in c# as follows
public class Vehicle
{
public string VehicleKey { get; set; }
}
Now I am building an array of VehicleKeys in javascript as follows
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = new Vehicle();
vehicleObject.data.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKey.push(vehicleObject.data);
}
return vehicleKeys ;
}
I am calling the $.post(url, data) as follows
var objectToSend = GetVehicleDetails(selectedVehicles);
var data = JSON.stringify({
'vehicles': objectToSend
});
$.post(url, data)
.done(function (result) {
if (result) {
download(result, 'VehicleReport.xlsx', { type: 'application/octet-stream' });
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function (error) {
console.log("Error creating report.");
});
The MVC Controller has a method to accept Vehicles with multiple VehicleKeys coming from javascript
public byte[] CreateVehicleReport(List<Vehicle> vehicles)
{
//Generation of report and pass it back to javascript
}
Here I am able to submit the data in javascript as 10 and 11 for Vehicles but when it catches the c#, the count is coming as 0.
Any help would be greatly appreciated.
$.post is not posted Content-Type json data so you need to use $.ajax
function GetVehicleDetails(inputarray) {
var vehicleKeys = [];
for (var i = 0; i < inputarray.length; i++) {
var vehicleObject = {}; // Set Object
vehicleObject.VehicleKey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
vehicleKeys.push(vehicleObject);
}
return vehicleKeys;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
$.ajax({ type: 'POST',
url: url,
data: JSON.stringify(objectToSend),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('data: ' + data);
},
}).done(function () {
if (result) {
console.log("Report created successfully");
}
else {
console.log("Error creating report");
}
}).fail(function () {
console.log("Error creating report.");
});
C# Method
[HttpPost("CreateVehicleReport")]
public byte[] CreateVehicleReport([FromBody]List<Vehicle> vehicles)
{
return null;
//Generation of report and pass it back to javascript
}
I used a similar approach once but with ajax and it went like this:
fill your array directly with the properties inside your class as object { } make sure the names are exactly the same:
function GetVehicleDetails(inputarray) {
var data_Temp = [];
for (var i = 0; i < inputarray.length; i++) {
var _vehiclekey = inputarray[i].VehicleKey ? inputarray[i].VehicleKey : null;
data_Temp.push({ VehicleKey : _vehiclekey });
});
return data_Temp;
}
var objectToSend = GetVehicleDetails(selectedVehicles);
var JsonData = JSON.stringify({ vehicles: objectToSend });
$.ajax({
type: "POST",
contentType: "application/json",
url: "/controllerName/actionName", //in asp.net using mvc ActionResult
datatype: 'json',
data: JsonData,
success: function (response) {
},
error: function (response) {
console.log(response);
}
});
And the ActionResult in the controller should look like this:
[HttpPost]
public ActionResult Create(List<Vehicle> vehicles)
{
//do whatever you want with the class data
}
I don't know if this is helpful for you but this always works for me and i hope it helps.
I have a array and I get data from the array and going to pass it to the controller through ajax call.
But the problem is it hits the controller side with all the null values.(Data not passes,null passes )
Client Side Code
for (var j = 0; j < NewsGlobalArray.length; j++) {
var NewsRequestModel = {
DESCRIPTION: NewsGlobalArray[j]['DESCRIPTION'] // news description comes here.i checked it with console.log
}}
$.ajax({
url: $('#addNewsRequest').val(),
type: "POST",
data: { newsRequest: NewsRequestModel },
dataType: "json",
success: function (referenceNo) {
//success
}
});
}
My Controller
[HttpPost]
public JsonResult AddNewsRequest(NewsRequestModel newsRequest) // hits here with null values
{
//Some coding goes here.
}
My Model
public class NewsRequestModel
{
public int NEWSREQUESTID { get; set; }
public string DESCRIPTION { get; set; }
}
Try this: just add traditional:true in ajax call
$.ajax({
type: "POST",
url: $('#addNewsRequest').val(),
data: JSON.Stringify({ newsRequest: NewsRequestModel }),
dataType: "json",
traditional:true,
success: function (res) {
//do something
}
});
I think you need to this:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
then pass myObject to ajax call and get on controller by name.
What I have:
A Model like this:
public class ProductModel
{
public string ProductName { get; set; }
public List<string> SkipUpdates { get; set; }
}
A controller method like this:
public ActionResult GetProductUpdates(ProductModel productModel)
{
return View("AddEdit");
}
Not doing anything for now just want to make sure that data from JS comes in correctly.
The JS:
function productModel() {
this.productName = "";
this.SkipUpdates = [];
}
Filling the model and AJAX:
var newProductModel = new productModel();
var options = $('#AdditionalSkipDates option');
var skipDates = [];
options.each(function (i, option) {
skipDates[i] = $(option).text();
});
newProductModel.productName = "ABC";
newProductModel.SkipUpdates = skipDates;
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: newProductModel,
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});
AdditonalSkip dates is a listbox with a bunch of dates in it.
What's happening:
The SkipUpdates array does have values which I can see in the browser's console.
Put a breakpoint in the controller and it hits the method.
The SkipUpdates value is null.
What's not happening:
How do I get the array to come-into the controller?
Thanks in advance.
Try to stringify the object before sending it:
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: JSON.stringify(newProductModel),
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});
My ajax call fails with the message in question.
[WebMethod(EnableSession = true)]
public static string UpdateTotalPrice(List<TicketPriceAjax> jsonTickets)
{
// some server-side processing
return "a string value";
}
The object Iʻm trying to pass
public class TicketPriceAjax
{
public string Fullname { get; set; }
public string Price { get; set; }
public string TicketDescription { get; set; }
}
My javascript which gets invoked on a change event
$("select.combobox").change(function(e) {
var ticketsArray = GetTicketsArray();
postTotalPrice(ticketsArray);
});
function GetTicketsArray() {
var tickets = {};
var prices = [];
tickets.prices = prices;
$("#divFullNames div.row").each(function () {
var price = {
"Fullname": $(this).find("input").val(),
"Price": $(this).find("select").val(),
"TicketDescription": $(this).find(":selected").text()
};
tickets.prices.push(price);
});
return tickets;
};
function postTotalPrice(prices) {
$.ajax({
type: "POST",
url: "Details.aspx/UpdateTotalPrice",
data: JSON.stringify(prices),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
UpdateTotalPrice(data);
},
error: function(data, textStatus, jqXHR) {
console.log('error!', data, textStatus, jqXHR);
}
});
};
What am I doing wrong?
Change data part to this
data: JSON.stringify({jsonTickets:prices})
Your webmethod expects a parameter with name jsonTickets so you need to specify parameter name in data part.
Also you do not need to assign tickets.prices simply create an array and push objects in it and pass it to webmethod.This way you are creating a list and than assigning list to its property prices and in webmethod you are expecting a list.
var tickets = [];
$("#divFullNames div.row").each(function () {
var price = {
"Fullname": $(this).find("input").val(),
"Price": $(this).find("select").val(),
"TicketDescription": $(this).find(":selected").text()
};
tickets.push(price);
This will pass list to webmethods.
I have the following script. It runs, it passes the variables to the controller, the controller executes correctly, but for whatever reason the success function does not fire and therefore does not refresh my html. Instead the error fires off. Nothing is jumping out at me as to the cause. Thanks for the help!
$(function() {
$("#btnUpdateTick").unbind('click').click(function () {
var currenttick =
{
"TicketID":#Html.Raw(Json.Encode(Model.TicketID)),
"Title": $("#Title").val(),
"Creator": $("#Creator").val(),
"StatusID": $("#StatusID").val(),
"Description": $("#Description").val(),
"newComment":$("#txtAddComment").val(),
Cat:
{
"CatID":$("#ddCurrTickCat").val()
}
}
//var newcomment = $("#txtAddComment").val();
var conv = JSON.stringify(currenttick);
$.ajaxSetup({cache:false});
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
});
});
My controller:
[HttpPost]
public PartialViewResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return PartialView("TicketDetails", model);
}
Your controller is returning a view instead of json. You should be returning a JsonResult instead. Try this:
[HttpPost]
public JsonResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return Json(model);
}
If you want to return Partial view from ajax call then modify ur ajax request as :
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "html",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
Now "data" in ur success function will have html returned from PartialViewResult().