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)
Related
I want to send array of numbers to my back action and I am getting NULL or error whatever I try. This is my current code.
JS
$.ajax({
traditional: true,
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: "POST",
data: JSON.stringify(groupIds),
url: '/Admin/ReadMessages',
error: function (error) {
swal.fire({
title: "Something went wrong. Please try again later.",
type: "error"
});
}
});
MVC
public ActionResult ReadMessages(List<long> groupIds)
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
Any ideas?
try this
var arr= new Array();
arr.push(1);
arr.push(2);
$.ajax({
type: "POST",
url: urlToPost,
data: JSON.stringify(arr),
contentType: "application/json"
});
Just to clear out for others, as #Amin stated and I realized, error was in sending NON array object, I was using map function and it returned some jquery array, but when I instantiated new Array and sent it, it worked perfectly.
$.ajax({
traditional: true,
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: "POST",
data: { 'groupIds': groupIds} ,
url: '/Admin/ReadMessages',
error: function (error) {
swal.fire({
title: "Something went wrong. Please try again later.",
type: "error"
});
}
});
And in Controller :
public ActionResult ReadMessages(IEnumerable<long> groupIds))
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
$.ajax({
traditional: true,
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: "POST",
data:{groupIds:groupIds},
url:'#Url.Action("ReadMessages", "Admin")',
error: function (error) {
swal.fire({
title: "Something went wrong. Please try again later.",
type: "error"
});
}
});
controller:
[HttpPost]
public ActionResult ReadMessages(IEnumerable<long> groupIds))
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
fromBody does not work in Web mvc Core 2.2 for Post
In Postman I am trying to post some data. I have made it as simple as possible;
iam see error 400 Bad Request
var UserVmodl =
{
In_User_Name:'',
In_Family :$("#Family").val(),
User_Name :$("#Name").val()
In_National_Code :$("#National_Code").val(),
In_Birth_Date_sh :$("#dateBirth_Date").val(),
In_Email:$("#Email").val()
}
$.ajax({
url: '#Url.Action("SaveUser", "PersonalInfo")',
type: 'POST',
data: JSON.stringify(UserVmodl ),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
beforeSend: function (request) {
sendRequestVerificationToken(request);
},
success: function (data) { localSuccess(data); onSuccessFunc(data); }
});
[Route("PersonalInfo")]
[Area("client")]
public class PersonalInfoController : Controller
{
[HttpPost]
[Route("save")]
public IActionResult SaveUser([FromBody] PersonalInfo UserVmodl)
{
//var Result= _IUserService.UpdateUser(UserVmodl);
return View();
}
}
Try to send RequestVerificationToken from headers if you need yo add antiforgery validation.
$.ajax({
url: '#Url.Action("SaveUser", "PersonalInfo")',
type: 'POST',
headers : {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(UserVmodl),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: function (data) { localSuccess(data); onSuccessFunc(data); }
});
Remember to add #Html.AntiForgeryToken() in your form.
Besides,you need to return a json result since your ajax needs a return type of json.
Ajax:
var test = "test";
$.ajax(
{
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { input: test },
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# function:
[WebMethod]
public void function(string input)
{
}
The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.
I have also tried setting the dataType to "text" with similar results.
What am I missing?
I would suggest that you shouldn't send your data as JSON. Just remove the
contentType: "application/json; charset=utf-8"
and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.
try this one may be resolve your issue
var test = "test";
$(document).ready(function () {
$.ajax({
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
datatype: "json",
data:JSON.stringify({ 'input': test }),
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
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
}
I am sending a collection of GUID-like objects to my MVC controller like so:
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
songIds: JSON.stringify(songIds)
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});
The data being sent in my request header looks like:
songIds:["6cb44f55-9fd5-4540-9b11-75ccce816d67"]
and my MVC3 controller method looks like:
[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
IList<Song> songs = songManager.GetByIds(songIds);
return new JsonDataContractActionResult(songs);
}
In this implementation I receive a non-null List object, but it is always empty. What's my mistake?
EDIT: If I POST like this instead of GET it works fine. How come??
$.ajax({
type: 'POST',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
songIds: songIds
}),
success: function (data) {
loadedSongs = loadedSongs;
if (callback) {
callback(data);
}
},
error: function(error) {
console.error(error);
}
});
You should try to use "traditional" option set to true for your jQuery Ajax request.
Refer to documentation for more details : http://api.jquery.com/jQuery.ajax/
And you should also remove the JSON.Stringify part.
Can you try this out and let me know if it worked out for you ?
I Did a test on my end and it works just fine.
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
traditional: true, //// traditional option to true
data: {
songIds: songIds /// no JSON.stringify
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});