I have read on so many forums that a lot of times model won't bind to the controller due to the parameter of the action has the same name of a field but I changed it to a unique names and I am still not getting it. I am passing the objects after obtaining them from the html pages and using JSON.Stringify to serialize it and everything looks perfect in the 'Payload request' if I debug it in chrome tool but as soon as it hits the controller, the model is null. what is wrong with the code?
Model:
public class JsonFileModel
{
public string[] Geo { get; set; }
public string[] State { get; set; }
public string[] Variables { get; set; }
public int[] Weights { get; set; }
public string[] Variable_Category { get; set; }
public string UID { get; set; }
}
AJAX Call:
var geo_graphic_level = $('input[name=geographic-radio-name]:checked').val();
var state = $('#states-select-id option:selected').val();
var v = $('#variable-list-select-id option:selected');
var variables = [];
var json = "'" + JSON.stringify(variables) + "'";
$(v).each(function (index, v) {
variables.push($(this).val())
});
var variable_category = $('#categories-select-id option:selected').val();
var weights = [];
$("input[name='weight-name']").each(function () {
weights.push(this.value);
});
//the above code gives the values for the objects
$.ajax({
type: "POST",
url: '@Url.Action("Save", "Drive")',
dataType: "json",
data: JSON.stringify({
Geo: geo,
State: state,
Variables: variables,
Weights: weights,
Variable_Category: variable_category
}),
contentType: 'application/json',
success: function (result) {
console.log(result);
},
error: function (result) {
}
});
Controller:
[HttpPost]
public JsonResult Save([FromBody] JsonFileModel d)
{
//code code
return Json("worked");
}
Well so I defined my properties wrong for example when I am only expecting string from Geo, I defined my model to expect [] array. After fixing it, everything is working perfect!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.