Chris Chris - 4 months ago 9
jQuery Question

how to place a newly created ID into LocalStorage?

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?

Answer

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