I am passing data to controller through Ajax call.
Following is the ajax code:
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List[i] = $(selectedItem).text();
});
var from_Month = $("#fromKPAMonthPicker").val();
var from_Year = $("#fromKPAYearPicker").val();
var to_Month = $("#toKPAMonthPicker").val();
var to_Year = $("#toKPAYearPicker").val();
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
success: function (data) {
$("#divList").html(data);
}
});
Controller action method:
[HttpPost]
public ActionResult _DataByFromTo(List<Int32> doj_Month_List, Int16 from_Month, Int16 from_Year, Int16 to_Month, Int16 to_Year)
{
return View();
}
It was working in my old code perfectly fine. I don't know whats the problem. because all data are passing perfectly except this array of jquery.
To disable deep serialization of objects you need to set traditional property to true.
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
traditional: true,
success: function (data) {
$("#divList").html(data);
}
});
When set to true it results in a shallow serialization.
Following link might be of help.
https://api.jquery.com/jQuery.param/
try using push
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List.push($(selectedItem).text());
});
Related
I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.
Check the code bellow. I am doing post a list of ProductId to my controller and wanted to receive it with view model called- UpdateProductStatus. but the problem with my current code is: ajax post it to controller successfully but the UpdateProductStatus cant grab any value of ProductId. This always returns null. Whats wrong i am doing here? Possibly in ajax i am doing wrong i think. How can i fix this to receive all ProductId as a list form controller? Thanks in advance
Controller:
[HttpPost]
public IActionResult UpdateProductStatus([FromBody]List<UpdateProductStatus> UpdateProductStatus)
{
return Json("ok");
}
View Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlexzWeb.ViewModels
{
public class UpdateProductStatus
{
public int ProductId { get; set; }
}
}
Jquery:
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push($(this).val());
});
for (var _allSelectedProductId in allSelectedProductId) {
allSelectedProductIdWithKey.push('ProductId'+':'+_allSelectedProductId);
}
console.log(allSelectedProductIdWithKey);
//var things = JSON.stringify(allSelectedProductIdWithKey);
var things = JSON.stringify({ 'UpdateProductStatus': allSelectedProductIdWithKey });
console.log(things);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
console.log('sssss');
},
failure: function (response) {
console.log('fffff');
}
});
Html:
<input type="checkbox" class="chkItems" value="1">
<input type="checkbox" class="chkItems" value="2">
<button id="btnActivate">Button</button>
Your current code is sending a payload like below for the ajax call.
{"UpdateProductStatus":["ProductId:0","ProductId:1"]}
Your action method argument is a list of UpdateProductStatus objects. So for model binding to work properly with your current action method parameter signature, your payload should be like below.
[{"ProductId":"1"},{"ProductId":"2"}]
There is no need to specify the parameter name. Just pass an array of items, each with a ProductId property and it's value.
var allSelectedProductIdWithKey = [];
$('.chkItems:checked').each(function () {
allSelectedProductIdWithKey.push({ ProductId: $(this).val() });
});
var things = JSON.stringify(allSelectedProductIdWithKey);
$.ajax({
contentType: 'application/json; charset=utf-8',
type: 'POST',
url: '/Products/AppendClientFilter',
data: things,
success: function (res) {
console.log('Successs', res);
},
failure: function (response) {
console.log('Error', response);
}
});
You can also remove the dataType in ajax call. jQuery ajax will guess the proper type from the response header and in your case you are going to return explicitly JSON.
To bind to your controller method, you need to send an array of objects containing a name/value pair for ProductId. To build your array of objects, use
$('#btnActivate').on('click', function () {
var allSelectedProductId = [];
$('.chkItems:checked').each(function() {
allSelectedProductId.push({ ProductId: $(this).val() });
});
var things = JSON.stringify({ UpdateProductStatus: allSelectedProductId });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Products/UpdateProductStatus',
data: things,
success: function () {
....
});
});
I have been trying to call my .cs method in the controller from jquery json and it gets called but the parameter passed is always null. Why? Even i checked in the console log and it shows the value being passed but somehow it doesn't get passed to the method. It's null.
$('#AppointmentDate').change(function () {
var AppointmentDate = '2018-04-30'; //document.getElementById('AppointmentDate').value;
$.ajax
({
url: '#Url.Action("GetTimeSlotsByDate", "Appointment")',
type: 'GET',
contentType: "application/json; charset= utf-8",
data: JSON.stringify(AppointmentDate),
dataType: 'json',
success: function (results) {
$("#fk_TimeSlotID").html(""); // clear before appending new list
$.each(results, function (i, slot) {
$("#fk_TimeSlotID").append(
$('<option></option>').val(slot.TimeSlotID).html(slot.FromTo));
});
console.log('Time slots returned');
console.log(AppointmentDate);
}
});
Method:
public ActionResult GetTimeSlotsByDate(DateTime? RequestedAppointmentDate)
{
TimeSlotsRepository TimeSlotsRep = new TimeSlotsRepository();
List<TimeSlotsModel> ListTimeSlotsModel = TimeSlotsRepository.getTimeSlotsByDate(RequestedAppointmentDate);
return Json(ListTimeSlotsModel, JsonRequestBehavior.AllowGet);
}
This is the rendered URL
http://localhost:13924/Appointment/GetTimeSlotsByDate?"2018-04-30"
You can convert your data to query string parameters and pass to server in
url as
somesite.com/Appointment/GetTimeSlotsByDate?RequestedAppointmentDate=your date
try this ,Its working for me
$('#AppointmentDate').change(function () {
// var AppointmentDate = '2018-04-30'; //document.getElementById('AppointmentDate').value;
$.ajax
({
url: '#Url.Action("GetTimeSlotsByDate", "Appointment")',
type: 'GET',
contentType: "application/json; charset= utf-8",
//data: JSON.stringify(AppointmentDate),
data: { RequestedAppointmentDate: "2018-04-30" },
dataType: 'json',
success: function (results) {
$("#fk_TimeSlotID").html(""); // clear before appending new list
$.each(results, function (i, slot) {
$("#fk_TimeSlotID").append(
$('<option></option>').val(slot.TimeSlotID).html(slot.FromTo));
});
console.log('Time slots returned');
console.log(AppointmentDate);
}
});
I have question about passing values with ajax. I have done something like this:
$('#zlozZamowienie').click(function () {
var wycieczki = [];
$("input[name=Id_wycieczki]:checked").each(function () {
var id = $(this).attr('id');
wycieczki.push(id);
});
var productModel = {
Id_oferty: $("#Id_oferty").val(),
Nazwa_oferty: $("#Nazwa_oferty").val(),
Data_od: $("#Data_od").val(),
Data_do: $("#Data_do").val(),
Cena_za_miejsce: $("#Cena_za_miejsce").val(),
iloscDni: $("#iloscDni").val(),
SelectedKwaterunek: $("input:radio[name=SelectedKwaterunek]:checked").val(),
IdWycieczek: wycieczki
};
$.ajax({
type: "POST",
url: '#Url.Action("Szczegoly", "Oferta")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'skomponowanaOferta': productModel}),
dataType: "json",
success: function () {
alert('Success');
},
error: function (xhr) {
alert(xhr.error);
}
});
return false;
});
Szczegoly controller
[HttpPost]
public ActionResult Szczegoly(SzczegolyOfertyViewModel skomponowanaOferta)
{
if (ModelState.IsValid) {
...
};
TempData["Szczegoly"] = szczegoly;
return RedirectToAction("ZlozZamowienie", "Zamowienia");
}
Zamowienia Controller
public ActionResult ZlozZamowienie()
{
var skomponowanaOferta = (SzczegolyOfertyViewModel) TempData["Szczegoly"];
SzczegolyOfertyViewModel podsumowanie = new SzczegolyOfertyViewModel();
if (SprawdzWycieczki(skomponowanaOferta.IdWycieczek))
{
...
};
return View(podsumowanie);
}
Which is passing data correctly but because of this return false statement my button do not redirect me anywhere. When I change this return to true or just delete it, this ajax pass nulls. What am I doing wrong?
EDIT: I have error from ajax like this:
Ok I found answer here
RedirectToAction not working after successful jquery ajax post?
and then I add this to my ajax:
location.href="url"
like as #vinayakj said
I have a weird problem in my ASP.Net WebApi application. I have this client side code:
var arr = [];
for (var i = 0; i < checkarray.length; i++) {
if (checkarray[i] == 1) arr.push(ids[i]);
}
console.log(arr);
$.ajax({
type: "post",
async: false,
url: "/api/Demande/ReservationAgendaByDrivers",
data: arr,
success: function (data) {
// ...
}
});
In the server side:
[HttpPost]
public IEnumerable<ReservationModel> ReservationAgendaByDrivers(int[] tab)
{
List<ReservationModel> outlst = new List<ReservationModel>();
List<ReservationModel> model = GetListReservation().ToList();
foreach (ReservationModel item in model)
{
if (!item.id_chauffeur.HasValue)
continue;
if (tab.Contains(item.id_chauffeur.Value))
outlst.Add(item);
}
return outlst.OrderByDescending(x => x.id_demande);
}
I get for example, as output in the browser, this array :
[7, 5, 1]
but the tab parameter in the server side is always null !!
I need to know :
What are the reasons of this error?
How can I fix my code?
For the ModelBinder to work correctly you need to provide the array in an object under the tab property. You should also remove the async: false as it is unspeakably bad practice to use it.
$.ajax({
type: "post",
url: "/api/Demande/ReservationAgendaByDrivers",
data: {
tab: arr
},
success: function (data) {
// handle the response here...
}
});
What are the reasons of this error?
int[] tab is expecting a var in the params named tab which is not there as you are trying to send an array arr.
How can I fix my code?
Send an object in the data :
data: { tab: arr }, // here tab is the key which belongs to int[] tab at backend
and async:false is not a good choice to set it to false. This shouldn't be used to set it to false as there are ways to do the things correctly with promises.
console.log(arr);
$.ajax({
type: "post",
url: "/api/Demande/ReservationAgendaByDrivers",
data:{tab:arr},
success: function (data) {
.............
}});
Thanks everybody,
I fix my code by editing my code like this :
$.ajax({
type: "post",
async:false,
url: "/api/Demande/ReservationAgendaByDrivers",
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
success: function (data) {
.......
}
});