Can't pass json object to contoller in asp.net web api - json

I am a newbie to web api,not able to find the error while passing json message to a web api controller. I am using fiddler client to post complex type(model object). My model is always null. It is not reading from the json post object. What am I doing wrong?
My model:
public class LocationModel
{
public int Customer {get; set;}
public string Name { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Area { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
My controller:
public class LocationController : ApiController
{
[HttpPost]
public bool AddLocation([FromBody] LocationModel model)
{
MysqlRepository reps = new MysqlRepository();
if (reps.LocationInsert(model))
{
return true;
}
else
{
return false;
}
}
}
Json message(post using fiddler client):
var LocationModel = {
Customer:9,
Name: "test",
AddressLine1:"rrr",
AddressLine2:"rrr",
Area:"ddd",
City:"ddd",
State:"cooo",
Country:"kkk"
}
$.ajax({
url: 'api/Location',
type: 'POST',
data: JSON.stringify(LocationModel),
dataType: 'json',
contentType: "application/json",
success: function (data) {
}
});

Being new to fiddler tool i passed header info at body ...thats why input not passed from tool....
correct way is to pass in fiddler body as:
{
"Customer":9,
"Name": "test",
"AddressLine1":"rrr",
"AddressLine2":"rrr",
"Area":"ddd",
"City":"ddd",
"State":"cooo",
"Country":"kkk"
}

Related

Aps.net core Razor page [FromBody] Ajax post Model always is null

In Asp.Net core I have a razor page and I want to send a Ajax post to a Post method but always I get null model.here is my simplify question.
public class IndexModel : PageModel
{
public void OnPost([FromBody]A A)
{
if (ModelState.IsValid)
{
}
}
}
and this is my model:
[JsonObject(MemberSerialization.OptOut)]
public class A
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string CityId { get; set; }
[JsonProperty]
public string Infected { get; set; }
[JsonProperty]
public string Susceptible { get; set; }
[JsonProperty]
public string Recovered { get; set; }
[JsonProperty]
public string CityName { get; set; }
}
This is my Ajax request:
function f(event) {
var token = $("input[name='__RequestVerificationToken']").val();
var c = {};
c["Id"] = "1";
c["CityId"] = "2";
c["Infected"] = "3";
c["Susceptible"] = "4";
c["Recovered"] = "5";
c["CityName"]=""
$.ajax({
url: "./DynamicEpidemic",
type: "post",
contentType: 'application/json; charset=utf-8',
headers:
{
"RequestVerificationToken": token
},
data: { A: JSON.stringify(c)},
success: function () {
alert("OK");
}
});
console.log(JSON.stringify(c));
}
and sent json object is like this:
{"Id":"1","CityId":"2","Infected":"3","Susceptible":"4","Recovered":"5","CityName":""}
but my model is always null.ModelState error is
Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
Try changing to data: JSON.stringify(c).

passing list with form.serialize

This is my javascript function to pass data from view to controller:
function UpdateCourse() {
debugger
SelectedIncharge();
SelectedAssistants();
SelectedParticipants();
var Course = $("form").serialize();
var model = {
courseData: Course,
SelectedInchargeList: SelectedInchargeList,
SelectedAssistantList: SelectedAssistantList,
SelectedParticipantList: SelectedParticipantList
};
debugger
$.ajax({
url: '#Url.Action("UpdateCourseDetails", "Course")',
type: 'POST',
dataType: 'JSON',
data: model,
// contentType: "application/json",
success: function (data) {
$('#CoursesSaveBtn').prop("disabled", false);
ShowStatus(data.Response);
hideWait();
GetCourseGrid();
},
error: function (xhr) {
$('#CoursesSaveBtn').prop("disabled", false);
var response = { "ResponseCode": 99, "ResponseMessage": "Validation Failed" };
var responseCode = JSON.parse(JSON.stringify(response));
ShowStatus(responseCode);
hideWait();
}
});
}
I am getting values in the model variable but i get only list correctly the courseData remains null. Here is my code of the view model.
public class CourseModel
{
//public Guid Id { get; set; }
//public string Name { get; set; }
//public string Description { get; set; }
//public string ClassRoom { get; set; }
//public DatabaseOperationType Operation { get; set; }
public CourseRequestDto courseData { get; set; }
public List<Guid> SelectedInchargeList { get; set; }
public List<Guid> SelectedAssistantList { get; set; }
public List<Guid> SelectedParticipantList { get; set; }
}
And my controller definition is as follows:
[HttpPost]
public ActionResult UpdateCourseDetails(CourseModel model)
{
}
$("form").serialize() returns a string with serialized values, like key1=value1&key2=value2. Your model expects CourseRequestDto, so there is probably an error while mapping a string instead of json.
My guess is that your courseData needs to be in json format. You can refer to this answer to get the form data: Convert form data to JavaScript object with jQuery

binding json string to a model in asp.net MVC

I have a json string and I want to parse it to the ASP.NET MVC controller and bind to my model. Here is the way I did it but its not working, because the book parameter in the action method is null.
Below is my json string:
function parseDAta() {
var jsonString = "{\"book\":[{\"id\":\"01\",\"author\":\"j.k.rowling\",\"price\":250,\"available\":true,\"editions\":[{\"id\":\"001\",\"name\":\"2017\"},{\"id\":\"002\",\"name\":\"2018\"}]},{\"id\":\"02\",\"author\":\"carlsom james\",\"price\":500,\"available\":false,\"editions\":null}]}";
$.ajax({
url: '/book/book',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonString,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
}
Below is my action method:
[HttpPost]
public ActionResult book(model book)
{
return null;
}
Below is my model:
public class model
{
public book[] book { get; set; }
}
public class book
{
public string id { get; set; }
public string availabity { get; set; }
public string Author { get; set; }
public int price { get; set; }
public edition[] edition { get; set; }
}
public class edition
{
public string name { get; set; }
public string id { get; set; }
}
The DefaultModelBinder is unable to bind your object because it expects a payload like this:
{"book": {"book":[]}}
So, the json should be
"{\"book\":{\"book\":[{\"id\":\"01\",\"author\":\"j.k.rowling\",\"price\":250,\"available\":true,\"editions\":[{\"id\":\"001\",\"name\":\"2017\"},{\"id\":\"002\",\"name\":\"2018\"}]},{\"id\":\"02\",\"author\":\"carlsom james\",\"price\":500,\"available\":false,\"editions\":null}]}}";
The json you have created would work if the action method was like this:
public ActionResult book(book[] book)
{
}
To avoid this confusion with having too many books, you can change the parameter of the Action method to:
public ActionResult book(model model)
{
}
and the json to:
"{\"model\":{\"book\":[{\"id\":\"01\",\"author\":\"j.k.rowling\",\"price\":250,\"available\":true,\"editions\":[{\"id\":\"001\",\"name\":\"2017\"},{\"id\":\"002\",\"name\":\"2018\"}]},{\"id\":\"02\",\"author\":\"carlsom james\",\"price\":500,\"available\":false,\"editions\":null}]}}";
Another way to do this would be to add FromBody attribute to the parameter like this:
public ActionResult book([FromBody]model book)
{
}
You'd need to add a System.Web.Http reference to use this attribute.
var jsonString = "{\"book\":[{\"id\":\"01\",\"author\":\"j.k.rowling\",\"price\":250,\"available\":true,\"editions\":[{\"id\":\"001\",\"name\":\"2017\"},{\"id\":\"002\",\"name\":\"2018\"}]},{\"id\":\"02\",\"author\":\"carlsom james\",\"price\":500,\"available\":false,\"editions\":null}]}";
first you needs to unescape which will gives you in format of json
In JS
var jsonString =unescape("{\"book\":[{\"id\":\"01\",\"author\":\"j.k.rowling\",\"price\":250,\"available\":true,\"editions\":[{\"id\":\"001\",\"name\":\"2017\"},{\"id\":\"002\",\"name\":\"2018\"}]},{\"id\":\"02\",\"author\":\"carlsom james\",\"price\":500,\"available\":false,\"editions\":null}]}");
console.log(jsonString);
$.ajax({
url: '/home/book',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonString,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
Controller
[HttpPost]
public ActionResult book(List<book> book)
{
return null;
}
Models
public class model //No need of this class,you can remove it
{
public book[] book { get; set; }
}
public class book
{
public string id { get; set; }
public string availabity { get; set; }
public string Author { get; set; }
public int price { get; set; }
public edition[] edition { get; set; }
}
public class edition
{
public string name { get; set; }
public string id { get; set; }
}

Error when binding json to model in .NET

Been struggling with a problem whole day. I´m getting a "415 error unsupported media type" from Postman when I'm trying to pass this JSON data.
{"MatrattId":"1","MatrattNamn":"Capri","Beskrivning":"abc","Pris":56,"MatrattTyp":"1"}
To this controller:
public IActionResult AddDish([FromBody]Matratt dish)
{
restaurantRepository.AddDish(dish);
return Ok();
}
Below is my model. The project is using entity framework DB first. (That is why the model class is partial)
public partial class Matratt
{
public Matratt()
{
BestallningMatratt = new HashSet<BestallningMatratt>();
MatrattProdukt = new HashSet<MatrattProdukt>();
}
public int MatrattId { get; set; }
public string MatrattNamn { get; set; }
public string Beskrivning { get; set; }
public int Pris { get; set; }
public int MatrattTyp { get; set; }
public virtual ICollection<BestallningMatratt> BestallningMatratt { get; set; }
public virtual ICollection<MatrattProdukt> MatrattProdukt { get; set; }
public virtual MatrattTyp MatrattTypNavigation { get; set; }
}
Any idea? Thanks in advance.
Set content type in ajax as "application/json" and add Accept headers.
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': url,
'data': JSON.stringify(data),
'dataType': 'json',
'success': function(resp){}
});

ASP.Net MVC3 JSON to Model

Can anyone lead me to examples showing how to convert incoming JSON to a Model in MVC3?
That's already handled for you by the framework.
So you define models:
public class MyViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public Complex Complex { get; set; }
public IEnumerable<Foo> Foos { get; set; }
}
public class Complex
{
public int Id { get; set; }
}
public class Foo
{
public string Bar { get; set; }
}
then a controller action taking this model:
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
...
}
and finally you hammer this controller action with a JSON request matching the structure of your view model:
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
id: 1,
name: 'john smith of course, why asking?',
complex: {
id: 3
},
foos: [
{ bar: 'the bar' },
{ bar: 'the baz' },
]
}),
success: function(result) {
alert('hooray');
}
});
http://james.newtonking.com/projects/json-net.aspx
I would add more, but the example code is also on that front page.