I was using MVC3 with AJAX. I was using AJAX within another AJAX. For the first AJAX request, it properly sends to the controller with data. But after returning from the AJAX request, I again posting the same data to another action. But second time the data comes null when coming to the controller. Please help me to fix this issue.
Code
$(document).ready(function () {
$('.deleteitems').live('click', function (e) {
var items = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items.push($(this).attr("Id"));
});
var json = JSON.stringify(items);
var perm = $("#Permission").val();
if (items.length != 0) {
if (perm == "True") {
$.ajax({
url: '/ItemControl/ItemControl/Catalogue_Check',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == "S") {
DelBibsAlso();
}
else {
DelItemsonly();
}
}
});
}
else {
$("#divMes").removeClass("Success");
$("#divMes").addClass("Error");
showError("Sorry you dont have Permission!");
}
}
else {
alert("Select any Items to delete");
e.preventDefault();
}
});
});
function DelItemsonly() {
var items2 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items2.push($(this).attr("Id"));
});
var itemjson = JSON.stringify(items2);
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": itemjson, "DelBib": 0 },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
function DelBibsAlso() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
var bibjson = JSON.stringify(items1);
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": bibjson, "DelBib": cond },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
Controller Code
public ActionResult Catalogue_Check(string[] id)
{
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
var Matched_BibID = (from asd in Db.Items
where ints.Contains(asd.Id)
select asd.BibId).ToList();
foreach (var idd in ints)
{
var bibid = (from bib in Db.Items where bib.Id == idd select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
return Json("S", JsonRequestBehavior.AllowGet);
}
}
return Json("N", JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteItems(string[] id, int? DelBib)
{
//var newid = id.Split(',');
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
foreach (var a in id)
{
int sel = Convert.ToInt32(a);
Item item = Db.Items.Single(i => i.Id == sel);
int Sess = Convert.ToInt16(Session["AccId"]);
string AdminName = User.Identity.Name;
bool Exist = Db.RouteOuts.Any(itm => itm.ItemId == item.Id);
if (!Exist)
{
weed.DeleteIt(item, Sess, AdminName);
var bibid = (from bib in Db.Items where bib.Id == item.Id select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
Db.ExecuteStoreCommand("update Bibs set Status= 'D' where Id={0}", item.BibId);
Db.SaveChanges();
}
}
}
return Json("S", JsonRequestBehavior.AllowGet);
}
function Test() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
//var bibjson = JSON.stringify(items1); **** Loose this line ****
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ "id": items1, "DelBib": cond }), // **** Items are stringified before posting ****
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});enter code here
}
else {
e.preventDefault();
}
Related
I have problem with passing data to select2 (ajax dynamic search) in edit mode on document ready.
I create test button which should add data on click and it doesnt work... Any ideas with that?
$('.select2').select2({
minimumInputLength: 3,
ajax: {
url: (...),
dataType: 'json',
data: function (params) {
return {
query: params.term
};
},
processResults: function (data, params) {
var resData = [];
data.forEach(function (value) {
if (value.name.toLowerCase().indexOf(params.term.toLowerCase()) != -1)
resData.push(value)
})
return {
results: $.map(resData, function (item) {
return {
text: item.name,
slug: item.slug,
id: item.id
}
})
};
},
},
});
$('#preselectObjectDataButton').on('click', function() {
var _array = []
var o = new Object;
o.id = 1;
o.text = "test";
o.slug = "test";
_array.push(o);
$('.select2').val(_array).trigger('change.select2');
});
I have a view model with an Ajax call to save data:
ViewModel = function (data) {
contractsAutocompleteUrl = data.ContractsAutocompleteUrl;
var self = this;
ko.mapping.fromJS(data, lineMapping, self);
self.save = function() {
self.isBeingSaved(true);
$.ajax({
url: data.SaveUrl,
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function(data) {
if (data.viewModel != null) {
ko.mapping.fromJS(data.viewModel, lineMapping, self);
};
}
});
},
I have some computed variables:
self.TotalSaturdayHrs = ko.pureComputed(function() {
var result = 0;
ko.utils.arrayForEach(self.Lines(),
function(line) {
result = addNumbers(result, line.SaturdayHrs());
});
return result;
}),
self.TotalSundayHrs = ko.pureComputed(function() {
var result = 0;
ko.utils.arrayForEach(self.Lines(),
function(line) {
result = addNumbers(result, line.SundayHrs());
});
return result;
}),
.
.
.
(all the way to Friday)
And a computed GrandTotal:
self.GrandTotalHrs = ko.pureComputed(function() {
var result = addNumbers(0, self.TotalSaturdayHrs());
result = addNumbers(result, self.TotalSundayHrs());
result = addNumbers(result, self.TotalMondayHrs());
result = addNumbers(result, self.TotalTuesdayHrs());
result = addNumbers(result, self.TotalWednesdayHrs());
result = addNumbers(result, self.TotalThursdayHrs());
result = addNumbers(result, self.TotalFridayHrs());
return result;
}),
Now after the Ajax call, the computed observables TotalSaturdayHrs are no longer computed observables, they are simply properties and so my GrandTotal calculation throws an exception.
Why is that and how do I fix this?
What your .save() function should look like (I have a hunch that this will solve your issue):
ViewModel = function (data) {
var self = this,
contractsAutocompleteUrl = data.ContractsAutocompleteUrl;
self.isBeingSaved = ko.observable(false);
self.Lines = ko.observableArray();
ko.mapping.fromJS(data, lineMapping, self);
self.save = function() {
self.isBeingSaved(true);
return $.ajax({
url: data.SaveUrl,
type: "POST",
data: ko.mapping.toJSON(self), // !!!
contentType: "application/json"
}).done(function (data) {
if (!data.viewModel) return;
ko.mapping.fromJS(data.viewModel, lineMapping, self);
}).fail(function (jqXhr, status, error) {
// error handling
}).always(function () {
self.isBeingSaved(false);
});
};
}
ko.mapping.toJSON() will only turn those properties to JSON that also went into the original mapping. ko.toJSON() in the other hand converts all properties, even the calculated ones like TotalSundayHrs.
My wild guess would be that the server returns the same JSON object it had received in the POST, complete with all the ought-to-be-calculated properties like TotalSundayHrs - which then messes up the mapping in your response handler.
I have two actions in a controller that are called via ajax:
[HttpPost]
public ActionResult Slider(HttpPostedFileBase file)
{
var imagem = System.Web.HttpContext.Current.Request.Files["SliderImage"];
string path = Global.GetAppSetting("CaminhoImagensSlider");
if(imagem != null && imagem.ContentLength > 0)
{
String caminho = Path.Combine(path, imagem.FileName);
db.ImagensSlider.AddObject(new ImagensSlider()
{
Caminho = caminho
});
db.SaveChanges();
Global.SalvarArquivo(caminho, imagem.InputStream);
}
SliderViewModel sliderViewModel = new SliderViewModel(caminhoImagensSlider);
return PartialView("_ImagensSliderPartial", sliderViewModel.Imagens);
}
[HttpPost]
public ActionResult DeletaImagensSlider(int[] imagens)
{
foreach(int id in imagens)
{
ImagensSlider imagemSlider = db.ImagensSlider.Where(i => i.IdImagem == id).Single();
db.ImagensSlider.DeleteObject(imagemSlider);
db.SaveChanges();
}
SliderViewModel sliderViewModel = new SliderViewModel(caminhoImagensSlider);
return PartialView("_ImagensSliderPartial", sliderViewModel.Imagens);
}
The first action works fine, but the second (DeletaImagensSlider) does not work. Checking the Chrome console I found that error:
The partial view '_ImagensSliderPartial' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Configuracoes/_ImagensSliderPartial.aspx
~/Views/Configuracoes/_ImagensSliderPartial.ascx
~/Views/Shared/_ImagensSliderPartial.aspx
~/Views/Shared/_ImagensSliderPartial.ascx
~/Views/Configuracoes/_ImagensSliderPartial.cshtml
~/Views/Configuracoes/_ImagensSliderPartial.vbhtml
~/Views/Shared/_ImagensSliderPartial.cshtml
~/Views/Shared/_ImagensSliderPartial.vbhtml
EDIT:
JS
$("#formSlides").on("submit", function (e) {
e.preventDefault();
var data = new FormData();
var files = $("#imagem").get(0).files;
if (files.length > 0) {
data.append("SliderImage", files[0]);
}
$.ajax(this.action,
{
type: 'POST',
data: $(this).serialize(),
contentType: false,
processData: false,
data: data,
success: function (result) {
$("#imagensContainer").html(result);
}
});
});
$(document).on('change', '[type=checkbox]', function (e) {
if (this.checked) {
imagensChecadas += 1;
imagens.push(this.id);
}
else {
imagensChecadas -= 1;
imagens.remove(this.id);
}
if (imagensChecadas > 0) {
$("#btnDeleteImages").show();
}
else {
$("#btnDeleteImages").hide();
}
});
$("#btnDeleteImages").on("click", function () {
if (confirm("Tem certeza que deseja deletar estas imagens?")) {
$.ajax("/Configuracoes/DeletaImagensSlider", {
type: 'POST',
data: JSON.stringify(imagens),
contentType: 'application/json',
success: function (result) {
$("#imagensContainer").html(result);
}
});
}
});
Why is this view found in one action but not in the other?
I solve the problem by puting the entire path: "~/Areas/Admin/Views/Shared/_ImagensSliderPartial.cshtml".
But I cant understand why it works in different ways in the two actions...
this is my controller action that returns json
public ActionResult MapTest(string date)
{
var locations = _db.EMP_LOCATION.Where(m => m.CURRENT_DATE.Equals(date));
return Json(locations,JsonRequestBehavior.AllowGet);
}
My scrip is here
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
Now my question is where i can give date parameter in $.ajax and how?
Just do something like:
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
data: JSON.stringify({ date: "your date" })
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
Best Regards
You can pass the value in URL like below :
var script = {
callAction: function () {
var dateVal= "Your date";
$.ajax({
url: 'Home/MapTest?date='+dateVal,
type:'GET',
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
dataType: "html",
data: { date : "03/25/2013" },
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};