I'm trying to make an AJAX Request to a method of iActionResult in my ASP.NET application. The request is getting to the method but when its passed along it has a value of null in my method. The value of selectedKommun is always a number when I check it in the console.
$(document).ready(function () {
$('#kommun').change(function () {
var selectedKommun = $("#kommun").val();
var fordonSelect = $('#fordon');
fordonSelect.empty();
if (selectedKommun != null && selectedKommun != '') {
$.ajax({
type: "POST",
url: "/avboka?handler=GetFordon",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "Id": selectedKommun },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data);
})
}
});
});
Here is my method where im sending my request. I have commended out some code just to check the value of Id.
[HttpPost]
public IActionResult OnPostGetFordon(int Id)
{
//if (!string.IsNullOrWhiteSpace(kommunFordonId) && kommunFordonId.Length == 3)
//{
// IEnumerable<SelectListItem> regions = _fordonRepo.GetFordon(kommunFordonId);
// var json = JsonConvert.SerializeObject(regions);
// return this.Content(json);
//}
//return null;
return new JsonResult(Id);
}
Instead of
contentType: "application/json; charset=utf-8",
try
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
This is because you are not sending JSON content, only an int.
You also don't really need to specify a datatype since you are only sending an int.
Related
I want to get new value from controller and set it to view when form submit.
Controller:
public JsonResult GetVoucherNo()
{
var voucherno = 1001;
var lastvoucherno = db.PaymentsAndReceipts.Where(x => x.StakeHolder.StakeHolderType.Name == "Supplier").OrderBy(x => x.VoucherNo).ToList().LastOrDefault();
if (lastvoucherno != null)
{
voucherno = lastvoucherno.VoucherNo.GetValueOrDefault() + 1;
}
return new JsonResult { Data = voucherno, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My Jquery function:
I just want to do when this function calls, I can get the value from controller action.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function () {
//don't know what to do here.
});
}
The data should be available in the done function argument like this:
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function (result) {
//don't know what to do here.
console.log(result);
//you should see the exact JSON you return from the controller
});
}
I done it with success.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '/Payments/GetVoucherNo',
dataType: "json",
success: function (result) {
console.log(result);
return $('#VoucherNo').val(result); //to set value in textbox.
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr, status, error);
}
});
}
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 know this question has been asked many times, I relly tried to follow many examples but every time, I fail for an unknown reason. So I'm going to show you my example a (very simple one) and I need someone to tell me what did I do wrong.
Starting with the controller (its name is Recherche) method:
public int getNote(string a,string b)
{
if(string.IsNullOrEmpty(a))
return 1;
else return 0;
}
As you can see I didn't use the variable b, but who cares it's just an example.
Now for the ajax method:
$.ajax({
type: "POST",
url: "/Recherche/getNote",
coententType: 'application/json',
dataType: 'json',
data:JSON.stringify({a:"a",b:"b"}),
success: successFunc,
});
function successFunc(data) {
document.getElementById('note').innerHTML = data;}
Try this
var a1='';
var b1='';
$.ajax({
type: "POST",
url: "/Recherche/getNote",
coententType: 'application/json',
dataType: 'json',
data:JSON.stringify({a:a1,b:b1}),
contentType: "application/json; charset=utf-8",
processData: false,
success: function (data) {
document.getElementById('note').innerHTML = data;
},
error: function (response) {
if (response != 1) {
alert("Error!!!!");
}
}
});
Controller
[HttpPost]
[WebMethod]
public ActionResult getNote(string a,string b)
{
if (a== null && b==null) return Json(0);
//Some Action send Result
return Json(data, JsonRequestBehavior.AllowGet);
}
I'm currently working on an ASP.Net MVC project.
I have a JavaScript function which takes an XML string as input. I would like to send this to the controller.
I have done so using an AJAX request, but in the controller the string is null.
View:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")'
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: xml,
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Controller:
public ActionResult Save(string xml)
{
Console.WriteLine(xml);
W6ViewModel viewModel = new W6ViewModel();
viewModel.engineers = db.W6ENGINEERS.ToList();
viewModel.tasks = db.W6TASKS.ToList();
viewModel.skills = db.W6TASKS_REQUIRED_SKILLS1.ToList();
var engList = new List<object>();
foreach (var engineer in viewModel.engineers)
{
engList.Add(new { key = engineer.ID, label = engineer.Name });
}
ViewBag.engineers = engList;
return View("Index", viewModel);
}
var xml = scheduler.toXML()
alert(xml):
Error Code (Sorry, wall of text):
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.QueryString value was detected from the client (xmlString="<data><event>
Name your parameter like this:
function save() {
var xml = scheduler.toXML();
alert(xml);
var url = '#Url.Action("Save", "Home")';
$.ajax({
url: url,
Type: "POST",
dataType: 'json',
async: false,
data: { xml: xml},
contentType: 'application/json; charset=utf-8',
success: function (data) { alert("OK");},
error: function (jqXHR, exception) {
alert('Error message.');
}
});
Also put this tag above you controller action:
[ValidateInput(false)]
See the following ajax call:
$.ajax({
url: '#Url.Content("~/myaccount/CheckDuplicateEmailAddress")',
data: { "emailAddress": email },
async: false,
type: "post",
success: success,
error: error
});
And controller action is below. you need to send param as this:
data: { "emailAddress": email }
Remember case sensitivity and double quotes:
public bool CheckDuplicateEmailAddress(string emailAddress)
{
}
I have a WebMethod, which is populating a JQuery DataTable with some initial values. I have a drop down list, which calls the WebMethod and try to populate it with different values. My problem, is if the JSON data is null (or '') then i get JSON.parse: unexpected end of data.
Now, I can check the length of the object using if(msg.d.length !- '' { build the table} ) However, if the length is null (''), then i never go into the build table, and therefore cant present that there is no data / no records.
How can I ensure that if the JSON string/object is null ('') that DataTables still presents No Records found etc...?
$('#ddBICS').change(function (e) {
var val = $('#dd option:selected').text();
msgDateDetail(val);
});
function msgDateDetail(value) {
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = JSON.parse(msg.d);
var asInitVals = new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}
msg could be null or undefined, just checking for the variable will tell you that. Also since you're using JQuery you could check if d is an array with the isArray JQuery method.
if(msg && msg.d && $.isArray(msg.d) && msg.d.length > 0) {
// build the table
}else{
// data is empty
}
Within your above method you would do the following.
function msgDateDetail(value) {
$('#tblMsgDate
$.ajax({
type: "POST",
url: "Default.aspx/MsgDateDetail",
cache: false,
data: JSON.stringify({ searchValue: value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var asInitVals = new Array();
var data = (msg && msg.d && $.isArray(msg.d))? msg.d : new Array();
otblMsgDateDetail = $("#tblMsgDateDetail").dataTable({
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aaData": data
})
}
});
}
The documentation for the jquery method is located on jquery.com http://api.jquery.com/jQuery.isArray/
For this to work make sure that your Default.aspx/MsgDateDetail returns application/json for the content type. To do this in the aspx file you do the following:
Response.ContentType = "application/json"
You must do this before you do any Response.Write
You should the length like this
if(msg.d.length !=0) { // Try this
//-- build the table
}