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>();
}
}
Related
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).
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
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; }
}
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"
}
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.