ASP.Net MVC3 JSON to Model - json

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.

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).

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){}
});

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

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"
}

JSON object(s) not binding to Model

Some objects in JSON are not binding to Model.
JS
var filterSet = {
"Filters":[Object1],
"FilterSets":[{
"Filters":[Object2,Object3],
"FilterSets":[{
"Filters":[Object4,Object5],
"FilterSets":[]
}]
}]
}
$.ajax({
url: '/ControllerName/GetData',
dataType: 'json',
data: JSON.stringify({
filterSet: filterSet
}),
type: 'POST',
contentType: 'application/json; charset=utf-8'
}).done(function (result) {
...
});
Controller
public JsonResult GetData(FilterSet filterSet)
{
....
return Json(data);
}
Model
public class Filter
{
public string Field1 { get; set; }
public string Field2 { get; set; }
...
public Filter()
{
...
}
}
public class FilterSet
{
public List<Filter> Filters { get; set; }
public List<FilterSet> FilterSets { get; set; }
public FilterSet()
{
Filters = new List<Filter>();
FilterSets = new List<FilterSet>();
}
}
The Filters list with Object4 and Object5 is bound, but the Filters list with Object1 and the Filters list with Object2 and Object3 are not. Or perhaps they are but are not getting populated with the correct values.
So all Filters siblings of non-empty FilterSets are just empty lists.
It doesn't seem to be the JS object causing this weird issue. I think it's something with the Model. What's missing from the Model? Or what's wrong in general?
Renaming the fields solved the issue. Perhaps, the pluralized field name was too close to the class name.
public class FilterSet
{
public List<Filter> FilterList { get; set; }
public List<FilterSet> FilterSetList { get; set; }
public FilterSet()
{
FilterList = new List<Filter>();
FilterSetList = new List<FilterSet>();
}
}