Got that error while try to call my controller's method (controller's name is ProductsController):
public ActionResult GetProducts()
{
return false;
}
Calling code like this:
$(document).ready(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetProducts", "ProductsController")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf8',
data: JSON.stringify(""),
})
Console in Chrome says:
jquery-1.10.2.js:8720 POST http
://localhost:56408/ProductsController/GetProducts 404 (Not Found)
Do you have any idea what is the problem?
Use the controller name prefix Products instead of ProductsController
$(document).ready(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetProducts", "Products")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf8',
data: JSON.stringify(""),
});
Asp.Net-MVC uses a naming convention for controllers.
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.
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'm calling a function in the controller using ajax. If there is an error in the controller, it goes to the Error.cshtml page, sends an error email from that page, but it won't render the Error.cshtml page on the screen, it stays on the page with the ajax call.
How do I fix that?
Here is the ajax call:
$("#County").change(function () {
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
failure: function (data) {
alert('failure');
},
});
});
Here is the customErrors from the main web.config:
<customErrors mode="On" defaultRedirect="~/Error" redirectMode="ResponseRedirect"/>
In your $.ajax definition you should use error property, not failure, check documentation. Like this:
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
error: function (data) {
alert('failure');
},
});
You also can get full error page like this:
error: function (httpRequest) {
console.log(httpRequest.responseText);
},
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);
}
});