Trouble accessing the property of a class in Ajax - ajax

In index.cshtml I am using Ajax. In click event of .removelink to get changes from action controller as follows:
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '' || recordToDelete != null) {
// Perform the ajax post
$.ajax({
//contentType: 'application/json',
//dataType: 'text',
type: 'post',
dataType: 'JSON',
url: '/ShoppingCart/RemoveFromCart/',
data: { id: recordToDelete },
success: function (data) {
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
}
else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
});
}
});
And in controller:
//AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public IActionResult RemoveFromCart(int id)
{
//Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
//string albumName = _context.Carts
//.Single(item => item.RecordId == id).Album.Title;
Cart cartt = ShoppingCart.getCartForGetalbumName(id);
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = HtmlEncoder.Default.Encode(cartt.Album.Title) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
//CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
}
However, it does not work. Additionally, the text of the tags does not change and fadeOut() does not work.
When I send a unit field (eg, a string or an integer) Jason reads it well.
However, when I send a class containing some properties (like the example above), its value in the data parameter is problematic.

Please modify your property to lowercase , try to use :
success: function (data)
{
if (data.itemCount == 0) {
$('#row-' + data.deleteId).fadeOut('slow');
}
else {
$('#item-count-' + data.deleteId).text(data.itemCount);
}
$('#cart-total').text(data.cartTotal);
$('#update-message').text(data.message);
$('#cart-status').text('Cart (' + data.cartCount + ')');
}

i add The following code to convert data to json in RemoveFromCart controller action:
var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);
and return json type :
[HttpPost]
public IActionResult RemoveFromCart(int id)
{
//Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
//string albumName = _context.Carts
//.Single(item => item.RecordId == id).Album.Title;
Cart cartt = ShoppingCart.getCartForGetalbumName(id);
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message ="محصول"+ cartt.Album.Title +
"از سبد خریدتان حذف گردید.",
CartTotal = cart.GetTotal(),
//CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Json(resulTtoJson);
also add the following code in view to convert data to javascript type:
var data =JSON.parse(dataa);
and use it:
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
// alert(recordToDelete);
if (recordToDelete != '' || recordToDelete != null) {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart/", { id: recordToDelete},
function (dataa) {
// Successful requests get here
// Update the page elements
var data =JSON.parse(dataa);
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
});
}
});

Related

JQuery Datatable memory leak under both IE and Chrome

My application is using Datatable which binds the data and event dynamically. When monitored from Developer tool in internet explorer one can see an increase in the total memory usage after each server successful response (increases approx. 29-35 MB). I tried solutions to free the DOM using jquery remove(), empty(), detach(), and destroy() methods but none stops the memory increase. Even destroying the datatable before request doesn't help. I also tried to delete the variables in the script, set the variables to null, and set the event bind to the datatable off().
The code snippet from the js file is as follows
function LoadData(isReset) {
var viewId = $jq('#ddlCategory').val();
if (viewId == 'undefined' || viewId == null || viewId == '') {
return false;
}
try {
//Clear the variables and remove the datatable
ClearFunction();
dtAjaxCall = $jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/GetData",
deferRender: true,
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
timeout: 0,
headers: { Connection: 'keep-alive' },
data: JSON.stringify({
"viewId": viewId
}),
success: function (response) {
//Clear the variables and remove the datatable
ClearFunction();
result = response.d;
if (result.IsError) {
CustomConfirm("dialog-confirm", result.Message, "");
}
else if (result.Data != null) {
data01 = result.Data;
result.Data = null; //set the result.Data as null
tableHeaders = ''; //var to store Datatable headers
columns = []; //var to store Datatable columns
excludeFilters = [];//var to exclude the filters.
bulkOperation = data01.BulkOperation; //var to store if bulk operation is required
//Create the table header columns dynamically as configured in database
$jq.each(data01.Columns, function (i, val) {
if (val.HiddenColumn != "Y") {
tableHeaders += "<th>" + val.DisplayName + "</th>";
var col = { 'title': val.DisplayName, 'data': val.DataColumnName.toLowerCase() };
columns.push(col);
}
if (val.FilterColumn >= 0) {
excludeFilters.push(val.FilterColumn);
}
});
data = $jq.parseJSON(data01.Results); //result returned in ajax call
json = $jq.parseJSON(data01.WorkListJQStructure); //datatable configuration returned in ajax call
delete json["bAutoWidth"];
json.data = data;
json.columns = columns;
DisplayExportOptions(json.buttons, 'resultsTable', 'ulExportTo');
//Add checkbox for each row in the data table
dtColumnDefinition = function (data, type, full, meta) {
return '<input type="checkbox" data-id="' + data + '">';
}
json.aoColumnDefs[0].render = dtColumnDefinition;
//Ajax call to save the datatable state state
dtSaveState = function (settings, data) {
$jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/SaveState",
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
data: JSON.stringify({ "viewId": viewId, json: data }),
"success": function () {
},
error: function (request, status, error) {
CustomConfirm("dialog-confirm", "An error occurred while processing your current request. Please try again", "");
}
});
}
//Try destroying the existing instance
if ($jq.fn.DataTable.isDataTable('#resultsTable')) {
$jq('#resultsTable').DataTable().destroy();
}
//Make the body empty
$jq('#resultsTable tbody').empty();
//Remove the datatable
$jq("#resultsTable").dataTable().remove();
//Datatable save state function call
json.stateSaveCallback = dtSaveState;
//Empty from the parent table of the datatable
$jq("#resultsTable_display").empty();
//Create the datatable header dynamically and add to the parent table
$jq("#resultsTable_display").append('<table id="resultsTable" class="display" style="width:100%;white-space: nowrap;"><thead><tr>' + tableHeaders + '</tr></thead></table>');
//bind the json and data to the datatable
SearchTable = $jq("#resultsTable").DataTable(json).rows().invalidate().draw();
//Set the event off before
$jq("#resultsTable").off();
//Set the event
$jq('#resultsTable').on('length.dt', function (e, settings, len) {
//code to set the height dynamically...
});
$jq("#resultsTable_display .dataTables_scrollHeadInner").css("width", "100%");
$jq("#resultsTable_display .dataTables_scrollHeadInner .dataTable").css("width", "100%");
BulkOpr(bulkOperation, SearchTable);
//reset the columns after binding the data
SearchTable.columns.adjust();
DataTableName = '#resultsTable';
$jq('#resultsTable').on('page.dt', function () {
info = SearchTable.page.info();
customHeight = 0;
customHeight = UserDefinedFields.CustomPageHeight(info, 40);
$jq('#Parent').attr('style', 'min-height:' + customHeight + 'px;');
});
$jq("a").removeClass("dt-button");
}
//set the variables null
json = null;
data01 = null;
data = null;
},
error: function (request, status, error) {
//do nothing...
}
});
return false;
}
finally {
//Clear the variables...
}
}
//----------------------------------------------
//method to clear the variables and datatables
function ClearFunction()
{
//make all variables null
dtAjaxCall = null;
resultSearchTable = null;
DataTableName = null;
info = null;
customHeight = null;
cells = null;
selected = null;
cBox = null;
clist = null;
dtSaveState = null;
result = null;
data01 = null;
tableHeaders = null;
columns = null;
excludeFilters = null;
bulkOperation = null;
data = null;
json = null;
dtColumnDefinition = null;
//clear dom objects
$jq("#resultsTable").dataTable().remove();
$jq("#resultsTable_display").dataTable().empty();
}
Thanks!
We are refreshing a datatable in a polling method, and it seems to lock up the browser. I don't have an answer either.

ASP.net cascading dropdown list

trying to implement country state dropdown in mvc but couldn't..
conotroller :-
[HttpGet]
public ActionResult GetCities(int StateId)
{
Business.Services.City cityService = new Business.Services.City();
List<Business.Models.City> stateList = cityService.GetCityByStateId(StateId);
//var jsonSerialiser = new JavaScriptSerializer();
//var json = jsonSerialiser.Serialize(stateList);
return Json(new { stateList }, JsonRequestBehavior.AllowGet);
}
method:
public List<Models.City> GetCityByStateId(int StateId)
{
try
{
var list = new List<SelectListItem>();
Collection<DBParameters> parameters = new Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "StateId", DBType = DbType.Int32, Value = StateId });
var city = this.ExecuteProcedure<Models.City>("GetCityByState", parameters).ToList();
//if (city != null && city.Count > 0)
//{
// list = city.Select(x => new SelectListItem { Text = x.CityName, Value = x.StateId.ToString() }).ToList();
//}
return city;
}
catch (Exception ex)
{
throw;
}
}
change event:
$('.ddlstate').change(function () {
debugger;
$.ajax({
url: '#Url.Action("GetCities", "User")',
type: "GET",
data: { StateId: $(this).val() },
dataType: "json",
success: function (result) {
debugger;
//alert(result.stateList[0].CityId);
$.each(result.stateList, function () {
debugger;
$('.cityddl').append($("<option></option>").val(CityId).html(CityName));
});
},
error: function (result, status, jQxhr) {
alert("Error: " + result + "-" + status + "-" + jQxhr);
}
});
});
i get count of the citites in method and controller but when i run project and change state dropdown i got blank city dropdown. what is wrong?
It looks like you're missing a couple of things in the $.each() call.
You should pass the JSON result from the ajax call to the $.each
You also need to provide a parameter to the callback function so that the callback function has something to work with
It could look something like this:
$.each(result.stateList, function(index, city) {
$('.cityddl').append($("<option></option>").val(city.CityId).html(city.CityName));
});

Pass multiple values of the same parameter for search method

I would like to update my search function, so that it would accept additional parameters, which will be builed dinamically with checkboxes(let's say for a location NY AND Tokio AND Berlin). For now, my controller accepts page number and a search string, which are called with Ajax for infinate pagination.
So my search link is now like: /TopEventsul?searchString=HouseParty
and would like to add more search functions like: /TopEventsul?searchString=HouseParty&Location=London&Location=Tokio
Can u please point me to the right direction or maybe give me some examples?
Bellow is my controller function
// GET: Ul
public ActionResult Index(int? pageNum, string searchString)
{
pageNum = pageNum ?? 0;
ViewBag.IsEndOfRecords = false;
if (Request.IsAjaxRequest())
{
var customers = GetRecordsForPage(pageNum.Value);
ViewBag.IsEndOfRecords = (customers.Any()) && ((pageNum.Value * RecordsPerPage) >= customers.Last().Key);
return PartialView("_TopEventLi", customers);
}
else
{
LoadAllTopEventsToSession(searchString);
ViewBag.TopEvents = GetRecordsForPage(pageNum.Value);
return View("Index");
}
}
public void LoadAllTopEventsToSession(string searchString)
{
var students = from s in db.TopEvents
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.Location.Contains(searchString)
|| s.Title.Contains(searchString));
}
var customers = students.ToList();
int custIndex = 1;
Session["TopEventi"] = customers.ToDictionary(x => custIndex++, x => x);
ViewBag.TotalNumberCustomers = customers.Count();
}
public Dictionary<int, TopEvents> GetRecordsForPage(int pageNum)
{
Dictionary<int, TopEvents> customers = (Session["TopEventi"] as Dictionary<int, TopEvents>);
int from = (pageNum * RecordsPerPage);
int to = from + RecordsPerPage;
return customers
.Where(x => x.Key > from && x.Key <= to)
.OrderBy(x => x.Key)
.ToDictionary(x => x.Key, x => x.Value);
}
Regards!
Here you have Location as fixed parameter, so you can simply do like these,
public ActionResult Index(int? pageNum, string searchString, IEnumerable<string> Location)
{
// Your code
}
if you have any other parameters you can also add them, for exa.
your parameter is param and it's type is int then
public ActionResult Index(int? pageNum, string searchString, int param)
{
// Your code
}
//Ajax Call for Index
function testAjax() {
$.ajax({
url: "#Url.Content("~/Your-Controller/Index")",
data: "pageNum=" + your data for pageNum + "&searchString=" + your searchString + "&param=" + param,
dataType: "json",
type: "Post",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
//Code for before send whatever you have to do.
},
success: function (data) {
//Your code when all ok
},
error: function (response) {
//Your code when error ocure
alert(response.responseText);
},
failure: function (response) {
//your code for failure
alert(response.responseText);
}
})
return false;
}

JQueryMobile: page with data (from ajax) doesn't change

function returnQueryResultJson(url,callback) {
return $.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(response) {
callback(response);
}
});
}
function showCategory(url,hash, options) {
var cat = hash.replace(/.*category=/, "");
if (cat == '#page1') {
cat = '';
}
var a = returnQueryResultJson('http://www.placetowebservice.nl/categories.php?category=' + cat,function(res) {
var
category = res,
pageSelector = hash.replace(/\?.*$/, ""),
$page = $(pageSelector),
$header = $page.children(":jqmData(role=header)"),
$content = $page.children(":jqmData(role=content)"),
markup = '<ul data-role="listview" data-theme="c" data-dividertheme="b">';
var cItems = category;
var headername = category.name;
var numItems = cItems.length;
if (cat == '') {
markup = '<ul data-role="listview" data-theme="c" data-dividertheme="b" style="min-height:100%;">';
}
for (var i=0;i<numItems;i++) {
markup += '<li><h3>' + cItems[i].title + '</h3><p>' + cItems[i].description + '</p></li>';
}
markup += "</ul>";
$header.find("h1").html(headername);
$content.html(markup);
$page.page();
$content.find(":jqmData(role=listview)").listview();
options.dataUrl = url;
options.changeHash = true;
options.reloadPage = true;
console.log($page);
$.mobile.changePage($page, options);
//}
});
}
$(document).bind("pagebeforechange", function(e,data) {
if (typeof data.toPage === "string") {
var
uz = $.mobile.path.parseUrl(data.toPage),
re = /^#category-item/,
re2 = /^#page1/
;
if (uz.hash.search(re) !== -1 || uz.hash.search(re2) !== -1) {
showCategory(uz.href,uz.hash,data.options);
e.preventDefault();
}
}
});
I have got this code, and it works pretty good (first time). I first load a page with:
$(document).ready(function(){
$.mobile.changePage('index.html#page1',{ dataUrl: "index.html#page1?category=", transition: "fade" });
});
It works, it loads the ajax-data in the page with id="page1".
Then I click on a link (category 1) and it shows the second page (with id="category-item") and fills it with the right data (category 1: sub 1, category 1: sub 2). Then I go back and it shows the categories again.
Now the problem appears, when I click on the next category (category 2). When I go to that page, it gives the right data from ajax (I used console.log to check this), but the data on the screen remains the data from category 1.
So the content from the first category you click on remains, even though you afterwards went to another category. It will remain showing the category you first clicked on.
What am I doing wrong?
It worked When I did this:
$page.page();
$page.trigger('create'); // added this one
$content.find(":jqmData(role=listview)").listview();
$content.find(":jqmData(role=listview)").listview("refresh"); // added this one

returning different javascript object from controller

my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}

Resources