Here is my ajax call:
var myIds = ["A","B","C"]
$.ajax({
type: "POST",
url: /DoStuffAndThings?year=2018&name=test,
data: {myIds: myIds},
traditional: false
});
Here is my controller action:
[HttpPost]
public void DoStuffAndThings(int year, string name, [FromBody] List<string> myIds) {
// do stuff
}
year and name come through without issue but myIds is always empty.
Ive tried
data: {myIds: myIds} and data: myIds and data: {"": myIds} and I tried using Ienumerable<string> and List<string> and string[]
and I've tried traditional: true and false
The model binder is unable to parse the send data as it does not know the format
Use JSON.stringify along with the corresponding parameters
var myIds = ["A","B","C"];
$.ajax({
type: "POST",
url: "/DoStuffAndThings?year=2018&name=test",
contentType: "application/json",
dataType: "json",
data:JSON.stringify(myIds),
traditional: false
});
The model binder should then be able to recognize the string collection in the body of the request.
When sending data to a web server, the data has to be a string.
Convert a JavaScript object into a string with JSON.stringify().
Before data, use JSON.stringify(myIds).
var myIds = ["A","B","C"]
$.ajax({
type: "POST",
contentType: "application/json",
dataType: 'json',
url: /DoStuffAndThings?year=2018&name=test,
data: JSON.stringify(myIds),
traditional: false
});
Related
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)
here is my ajax method
fl = new FormData();
fl.append("abcd", $("#so_camera_click")[0].files[0]);
debugger;
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
dataType: "json",
traditional: true,
data: {
f:fl,
}});
and C# controller is
the id so_camera_click is <input type="file" accept="image/*"/> every time i debug javascript there is data in fl variable but when it hits back end c# controller it gets null
public JsonResult AddSaleOrderToDB(HttpPostedFileWrapper f)
{
}
In your ajax request,
Change the value of data as follows,
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
traditional: true,
processData: false,
contentType: false
data: fl
});
Use Proper, readable field names.
Your controller is expecting a File and not a JSON data.
You'll want to post FileData and not json.
Additionally, for the Controller to map your posted values the argument must have the same name as you have used for the POST.
So for your example to work you'll have to do something like this
fl = new FormData();
fl.append("file", $("#so_camera_click")[0].files[0]);
debugger;
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
data: fl,
contentType: false,
processData: false
});
And in your Controller
public JsonResult AddSaleOrderToDB(HttpPostedFileWrapper file)
{
}
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 a newbie at javascript and jquery and I would like some help if possible. I searched and tried to make it work, but I think I am missing something simple.
I have the following method in my cs file (CeduleGlobale.aspx.cs)
[WebMethod]
public static void SetSession(string data)
{
HttpContext.Current.Session["salesorderno"] = data;
}
I also have a some javascript in my ascx file
<script type="text/javascript">
function SetSession() {
var request;
var values = 'fred';
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
request.done(function () {
alert("Finally it worked!");
});
request.fail(function () {
alert("Sadly it didn't worked!");
});
}
</script>
The function in the script is called by
<dx:ASPxCheckBox ID="cbxHold" runat="server" AutoPostBack="true" Text="OnHold" ClientSideEvents-CheckedChanged="SetSession">
</dx:ASPxCheckBox>
And the result i keep getting is "Sadly, it didn't work!".
I know the problem is not with anything relative to the path of the url, because it worked when i passed NULL as data and had the method with no parameters.
The parameters and data is what i tripping me I believe.
You should pass serialized JSON into the method:
var values = JSON.stringify({data:'fred'});
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
You are specifying that you are sending JSON, but you don't serialize the value to JSON, so try changing the request to this:
request = $.ajax({
type: "POST",
url: "CeduleGlobale.aspx/SetSession",
data: JSON.stringify({data: values}), // 'stringify' the values to JSON
contentType: "application/json; charset=utf-8",
dataType: "json"
});
'fred' is not json nor object
use object notation :
{"myattr":"fred"} //you can also do {myattr:"fred"}
and then use JSON.stringify which transform it into STRING representation of json object.
The data sent through post should be sent in a {key:value} format
values={name:'fred'}
The data should be passed into [key:value] pair.
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);
}
});