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);
}
Related
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.
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 problem with passing string value from jQuery to C# in Web MVC.
There is my jQuery code:
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: newPhone,
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
Here is my C# method:
[HttpPost]
public ActionResult ChangePhoneNumber(string data)
{
return View();
}
While debugging data parameter is always null.
What I am doing wrong?
Ok I`ve figured out what was wrong:
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({data: newPhone}),
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
I had to add data: JSON.stringify({data: newPhone}),
You were almost there;
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: {data: newPhone, foo: bar, fooz: barz}, //<-- mind the array here
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
Which will result the following;
[HttpPost]
public ActionResult ChangePhoneNumber(string data, string foo, string fooz)
{
//data will contain newPhone
//foo will contain bar
//fooz will contain barz
return View();
}
Just make sure to put the object in an array. So, in your case:
data: {data: newPhone},
will solve your problem.
You are not passing data correctly in ajax call. You need to pass it like this data: {data: newPhone},
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: {data: newPhone},
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
[HttpPost]
public ActionResult ChangePhoneNumber(string data)
{
return View();
}
you need post your data as form object; some useful information can found here
$.ajax({
type: 'POST',
url: '/Account/ChangePhoneNumber',
contentType: "application/json; charset=utf-8",
data: {data: newPhone},
dataType: 'json',
success: function (result) {
alert("We returned: " + result);
}
})
Check how you defined the route.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{data}",
defaults: new { controller = "yourcontroller", action = "actionname", data = UrlParameter.Optional }
);
Please check if the parameter name in your route is "data"
If you are not worried about AJAX/JSON, you can simply use $.Post method.
var url = "#Url.Action("ChangePhoneNumber", "Account")";
$.post(url, { data: newPhone })
.fail(function() {
// do something
})
.done(function(result) {
alert("We returned: " + result);
});
This is supposedly very easy but for some reason it has taken me about 2 hours and countless searches and nothing is working
I am trying to call a WebMethod from ajax, and it works quite well.
As soon as I try to change the c# function to accept parameters and send one from ajax everything fails
Code:
c#:
[WebMethod]
public static string GetBGsForSelectedCrop(string cropName)
{
return "asdasd";
}
jquery:
$().ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: "Wheat",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
});
I have tried datatype: "json", contentType: "application/json; charset=utf-8", and tried without both and datatype: "string" and datatype: "text", GET, data: "{'ABCD'}, data:{"cropName: Wheat"}, and data: json.Stringify("Wheat").
I get undefined for msg.d and sometimes HTTP error 500 if I take it too far.
What am I missing? It is just a simple task and should've been done in seconds..
As the guys in the comments says, you need to change your code for:
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetBGsForSelectedCrop",
data: JSON.stringify({ cropName: "Wheat" }),
dataType:'text',
contentType: "application/json; charset=utf-8",
success: function (msg) {
$("#Result").text(msg.d);
alert(msg.d);
console.log(msg)
}
});
});
Your error is the data is no good encoded, and you are missing the datatype.
What is the stringfy It Convert any value to JSON.
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);
}
});