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);
}
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 a List which look like the following
I want to send this list into my controller,
I am using ajax call to send data from client side to server side
here is my ajax call
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and my method in controller
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
here my List<Holidaysclass> data is showing null
what can I do here?
To send data from browser to controller you need to use POST type and then pass data inside ajax call. you can directly map your entites in action method.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and in controller put HttpPost Data Annotation
[HttpPost]
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
Using ajax get method we cant send data from client to server is not best way. try using POST method send data from client to server.
Reference : https://api.jquery.com/jquery.post/
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
......
});
You can do it like this :
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
Please follow this link for more information :
link
You can not post data in get request. Instead you need to use POST type request.
Here is your updated request.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
Also your action should have [HttpPost] annotation.
try this:
$.ajax({
url: '/Main/updateHoliday',
data: {list: d.weekendLeave},
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
[HttpPost]
public bool updateHoliday(List<Holidaysclass> list)
I have used the JavaScript code to call a method in the c# class (method provided in code). When is does a post back I get an error 500, I would like to know how I can fix this so that I call the method.
JavaScript to call c# class method
$.ajax({
type: "post",
url: "TestChapter.aspx/timeFinished",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//
}
});
Method in C# class testchapter.aspx:
[System.Web.Services.WebMethod]
public void timeFinished() {
// my code is here
}
Try this method in C# class testchapter.aspx, it might work:
[System.Web.Services.WebMethod]
public static void timeFinished() {
// my code is here
}
Have a look at this post
One thing is that you certainly missed the / char in your ajax method url, it should be:
url: "/TestChapter.aspx/timeFinished",
The other thing is that you should log the error to the console, it's easier that way:
$.ajax({
type: "post",
url: "/TestChapter.aspx/timeFinished",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// do something
},
error: function (data) { // handle your error loging in here
var errorDetails = data.responseText.replace("{", "").split(',');
var errorMessage = "";
for (var i = 0; i < errorDetails.length; i++) {
if (errorDetails[i].split(':')[0] == "\"Message\"") {
errorMessage = errorDetails[i].split(':')[1];
}
}
alert("Error:" + errorMessage);
});
It will write all errors in the debugger console, it's a lot easier to find errors.
I have write down a script as following
var reason = prompt("Please Enter the Reason", "");
if(reason != null)
{
// alert('you are here');
$.ajax({
type: "POST",
url: "/Controller/ActionMethod",
content: "application/json; charset=utf-8",
dataType: "json",
data: Json.stringify(reason),
success: function(){ alert('Data Sent');}
});
}
which works fine as it calls the ActionMethod from the controller but i am not being able to retrieve data taken with the help of prompt. within the controller.
I have tried
String reason = Request["reason"];
as well as i have tried to pass the data as argument in controller
public ActionResult ActionMethod(int id, string reason)
but in all cases reason is null. please tell me how can i retrieve the reason from the same.
thanks in advance
$.ajax({
type: 'POST',
url: "/Controller/ActionMethod",
data:{'reason':reason},
dataType: 'json',
success: function(jsonData) {
},
error: function(error) {
}
});
Your action maybe like this
[HttpPost]
public ActionResult ActionMethod(string reason){
...
return Json(obj);
}
this should work: Request.Form["reason"].
I am trying to post to a method using jQuery and Ajax. My Ajax code is as follows:
var isMale = $(e.currentTarget).index() == 0 ? true : false;
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: { isMale: isMale },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
And here is my WebMethod:
[WebMethod]
public static void SetUpSession(bool isMale)
{
// Do stuff
}
I get a 500 (Internal Server Error) looking at the console, the method never get's hit. After I changed data to "{}" and removed the bool from the method signature the method then gets hit, so I'm assuming its something to do with the Ajax.data attribute I'm trying to pass.
Two things you need to modify :-
1) Make sure that this line is written in your web service page and should be uncommented.
[System.Web.Script.Services.ScriptService]
2) Modify the "data" in the code as :-
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: '{ isMale:"' + isMale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
// Go to next question
}
});
Pass string instead of bool
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}
Alternative you can use pagemethods through script manager.
Try following code:
var params = '{"isMale":"' + $(e.currentTarget).index() == 0 ? true : false + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/SetUpSession",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
responseType: "json",
success: function (data) {}
});
[WebMethod]
public static void SetUpSession(string isMale)
{
// Do stuff
}