post json string to mvc action via ajax comes null - ajax

I am posting a json object via ajax
$('#btnOrder').click(function (e) {
var jsonData =
{
ScheduleDate: '20/07/2015 17:00',
UnitNumber: '425196',
Length: 0.00
}
var url = "http://mywebsite.com/Home/MakeOrder";
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: JSON.stringify(jsonData),
contentType: "application/json",
success: function(result) {
}
});
});
to the following action:
[HttpPost]
public PartialViewResult MakeOrder(string jsonData)
{
// some actions
return this.PartialView("_Summary", summaryModel);
}
Model:
public class OrderItem
{
public DateTime? ScheduleDate {get;set;}
public string UnitNumber {get;set;}
public float Length {get;set;}
}
The jsonData parameter value always comes null.
When I turn it into get ajax call via
var url = "http://mywebsite.com/Home/MakeOrder/?jsonData=" + jsonData
then the parameter comes fine as json string.
I need to send it via post.
EDIT ***** JS values
I'm debugging in Chrome and jsonData passed to 'ajax data:' is
JSON.stringify(jsonData)
gives
jsonData={"ScheduleDateTime":"20/07/2015 17:00","UnitNumber":"425196","Length":0.00}
if passed non stringified is:
jsonData = Object {"ScheduleDateTime":"20/07/2015 17:00","UnitNumber":"425196","Length":0.00}

Similar SO question that will solve your issue
You will need to probably create an model to accept a list of instead of a list of strings.
public class MyJSONObject{
public DateTime ScheduleDate { get; set; }
public string UnitNumber { get; set; }
public double Length { get; set; }
}
And accept it in your controller like:
[HttpPost]
public PartialViewResult MakeOrder(List<MyJSONObject> jsonData)
{
// some actions
return PartialView("_Summary", summaryModel);
}
And if it's not a list you need then just send off the single object and accept it in your controller as MyJSONObject jsonData instead.

Related

Can't send Post Data from Ajax to asp.net core web api?

I need to send an ajax request to a post method defined in my asp.net core web api as below :
// POST: api/Entreprise/Inscription
[HttpPost("Inscription")]
public IActionResult Post([FromBody] UserInfos value)
{
return Ok("value 1");
}
and this is UserInfos model:
public class UserInfos
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string domainName { get; set; }
public string phoneNumber {get;set;}
public string address { get; set; }
public string city { get; set; }
public string zip_code { get; set; }
}
I tested it with postman , by setting the header as 'Content-Type':'application/json' and in the body choosed raw and passed this json object :
{
"firstname" :"ahmed",
"lastname":"haddad",
"email":"haddad-a#live.fr" ,
"domainName":"easyappointments-master" ,
"phoneNumber":"25276164",
"address":"ariana" ,
"city":"grand tunis",
"zip_code":"4100"
}
and i get it to work, however when i call it from ajax i get BAD REQUEST 400 , this is my ajax code:
var newData={
"firstname" :"ahmed",
"lastname":"haddad",
"email":"haddad-a#live.fr" ,
"domainName":"easyappointments-master" ,
"phoneNumber":"25276164",
"address":"ariana" ,
"city":"grand tunis",
"zip_code":"4100" ,
};
var dataJson= JSON.stringify(newData);
$.ajax({
url:'http://test.example.fr/wsexample/api/Entreprise/Inscription',
dataType:'json',
data:dataJson,
ContentType:'application/json',
type:'post',
success:function(data,status){
console.log('the request is '+status+' the data is '+data);
},
error:function(html,status,error){
console.log('the request is '+error);
}
});
Note: the asp.net core web api and the ajax codes are in different servers ,so different domains , i have enabled the access to CORS for my domain in startup.cs , so normally that shouldn't trigger an issue.
also i have made succeded get requests to that webservice
I think the error has to do with your
ContentType:'application/json',
It should be
contentType: 'application/json',
and also remove this
dataType: "json"
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired. Read more here: Ajax request returns 200 OK, but an error event is fired instead of success
I got this to work:
EnterpriseController.cs
public class EnterpriseController : Controller
{
public async Task<IActionResult> Index()
{
return View();
}
[HttpPost]
[Route("api/[controller]/Inscription")]
public IActionResult Post([FromBody] UserInfos value)
{
return Ok("value 1");
}
}
Index.cshtml
#section Scripts {
<script>
$(document).ready(function () {
var newData = {
"firstname": "ahmed",
"lastname": "haddad",
"email": "haddad-a#live.fr",
"domainName": "easyappointments-master",
"phoneNumber": "25276164",
"address": "ariana",
"city": "grand tunis",
"zip_code": "4100"
}
$.ajax({
url: '/api/Enterprise/Inscription/',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(newData),
success: function (data, status) {
console.log('the request is ' + status + ' the data is ' + data);
},
error: function (html, status, error) {
console.log('the request is ' + error);
}
});
});
</script>
}
Console:
the request is success the data is value 1
removing [FromBody] from the controller
2.below the controller class use this [ApiController]
3.use this for post
$.ajax({
url:'http://test.example.fr/wsexample/api/Entreprise/Inscription',
data:JSON.stringify({
"firstname" :"ahmed",
"lastname":"haddad",
"email":"haddad-a#live.fr" ,
"domainName":"easyappointments-master" ,
"phoneNumber":"25276164",
"address":"ariana" ,
"city":"grand tunis",
"zip_code":"4100" ,
}),
type:'post',
headers: {
'Content-Type': 'application/json'
},
success:function(data,status){
console.log('the request is '+status+' the data is '+data);
},
error:function(html,status,error){
console.log('the request is '+error);
}
});
4.put [IgnoreAntiforgeryToken] top of your actionresult

Ajax Post web api model null

I saw o lot of this questions here and i tried everything but still dont work, so this is my last try
this is my js:
var test = { backlog: "backlog", todo: "todo", done: "done"};
$.ajax({
type: 'POST',
data: JSON.stringify({ data: test }),
url: "Post",
contentType: 'application/json'
}).done(function (res) {
console.log('done' , res);
});
my controller: testt is null.
[HttpPost]
public test Post([FromBody] test testt)
{
test data = testt
return data;
}
my model:
public class test
{
public test(){}
public string backlog { get; set; }
public string todo { get; set; }
public string done { get; set; }
}
the problem is i send the data to the server but the json dont bind with the model
if i use this :
[HttpPost]
public test Post([FromBody] JObject testt)
{
test data = testt["data"].ToObject<test>();
return data;
}
will work but i dont want to do this i want the automatic bind cuz will be much much easier with complex data.
i'm sorry for duplicate but i dont know what to do anymore.

Failed to post complex object in asp.net core api using jquery ajax

Failed to post complex object with list to asp.net core api using jquery ajax
Here is the Models
public class Bus
{
public int BusId { get; set; }
public string RegistrationNo { get; set; }
public IEnumerable<BusSeat> BusSeats { get; set; }
}
public class BusSeat : CoreModel
{
public int DecNumber { get; set; }
public int SeatId { get; set; }
}
Here is the Controller
[HttpPost]
public IActionResult Save([FromForm] Bus bus)
{
return Ok(bus);
}
Here is the javascript
var d = {
BusId: 1,
RegistrationNo: 'REG123',
BusSeats: [
{
DecNumber: 1,
SeatId:2,
},
{
DecNumber: 1,
SeatId: 4,
}
]
}
$.ajax({
type: 'post',
url: 'http://localhost:46060/api/bus/save',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ bus: d }),
success: function (data) {
},
error: function (data) {
}
});
Request is successful, but i couldn't get any data. Anything i am missing?
You don't need stringify, contentType on ajax call, and don't need [FromForm] on the mvc action.
Just pass the complex object directly on the data parameter.
$.ajax({
type: 'post',
url: 'http://localhost:46060/api/bus/save',
dataType: 'json',
data: d,
success: function (response) {
},
error: function (response) {
}
});
As long as the complex json object matches the view models you define, the binding should 'magically' work.
[HttpPost]
public IActionResult Save(Bus bus)
{
return Ok(bus);
}
This is off topic but you should think about how you construct your uris since you're building web api. You don't want to still use good old RPC style on your uri.
Think about the controller name as resource collection, and use HttpMethod as verb.
So I would create BusesController instead of BusController (Or use [RoutePrefix("api/buses")]), because I think about the resource as a collection - buses.
[Route("api/[controller]")]
public class BusesController : Controller
{
// GET api/buses
[HttpGet]
public IActionResult()
{
// Return all buses
return OK(...);
}
// GET api/buses/1
[HttpGet]
public IActionResult(int id)
{
// Return individual bus
return OK(...);
}
// POST api/buses
[HttpPost]
public IActionResult Post(CreateBusViewModel model)
{
// Create a new bus and return newly created uri of the bus
return Created(...);
}
}
You can read more about Richardson Maturity Model here!
Change the From part in the action to [FromBody] and in the ajax call for data just say
data: JSON.stringify(d)
Rather than
data: JSON.stringify({ bus: d })

pass complex data to get call if api

I am trying to pass a viewmodel data to get call in web api..
here is the viewmodel properties
public class FilterViewModel
{
public int RegionID { get; set; }
public int StateID { get; set; }
public int DistrictID { get; set; }
public int UniversityID { get; set; }
public int CollegeID { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
}
here is the ajaxcall that i am trying to ..
to convert formdata to json object
function toSimpleJson() {
});
return json;
}
the ajax call
function GetFilteredRecords() {
var filterOptions = toSimpleJson();
$.ajax({
url: '/api/workassign',
data: JSON.stringify(filterOptions),
cache: false,
type: 'GET',
dataType: 'JSON',
success: function (data) {
debugger
}
});
}
here is the filteroptions data
here is the api controller get action
public IEnumerable<WorkAssignViewModel> Get([FromUri]FilterViewModel date)
{
}
here i am getting the form data into json object and the passing to controller by using json.stringify() which is suggested and in controller using [FROMUri] but still values are null......
please suggest me a solution to overcome
thank you..
You need to remove the JSON.stringify() andcontentTypefrom the ajax call. You making a GET and a GET does not have a body (thereforecontentType` option is pointless). You code ajax call should be
$.ajax({
url: '/api/workassign',
data: filterOptions,
cache: false,
type: 'GET',
dataType: 'JSON',
success: function (data) {
debugger
}
});
Note that is you have generated you form controls correctly based on the view having #model FilterViewModel and using the HtmlHelper methods to generate the form controls (#Html.TextBoxFor(m => m.RegionID) etc), then you can simply use data: #('form').serialize(),

Is there a way to pass a "C#" object to a controller via AJAX?

It's simple enough to pass a string to a controller action via jQuery ajax, but is it possible to serialize a group of variables into an object, send it to the controller, and have the controller recognize it as an object?
For example:
In the server, you have a class Obj as such:
class Obj{
string a; int b; double c;
}
And in the controller, you have a method that is expecting an Obj object
public JsonResult UpdateObj(Obj obj){
//stuff
}
Is there a way in Jquery to serialize some JavaScript vars into a class Obj and then send it to an MVC controller action via an AJAX post?
Sure, let's suppose that you have a strongly typed view:
#model Obj
<script type="text/javascript">
// Serialize the model into a javascript variable
var model = #Html.Raw(Json.Encode(Model));
// post the javascript variable back to the controller
$.ajax({
url: '/home/someAction',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.serialize(model),
success: function(result) {
// TODO: do something with the results
}
});
</script>
and in the controller action:
public ActionResult SomeAction(Obj obj)
{
...
}
Just a remark about this Obj, make it have public properties instead of some fields:
public class Obj
{
public string A { get; set; }
public int B { get; set; }
public double C { get; set; }
}
jQuery :::
.ajax{
type: "POST",
url: "yourUrl/UpdateObj",
data: $("someHTMLForm").serialize(),
contentType: "application/json; charset=utf-8"
success: function(data){
//data will house your JsonResult
}
}

Resources