I have a controller
[HttpPost]
public async Task<IActionResult> Report([FromBody][FromForm] ReportViewModel request)
{
var x = request.StartDate; // binds data
var y = request.Pager.RowsPerPage; // always NULL
}
The ReportViewModel is
public class ReportViewModel : IEntity, IResponse
{
public string DateRange { get; set; }
public Pager Pager { get; set; }
}
public class Pager
{
public int CurrentPage { get; set; }
}
I am calling the Controller using AJAX, this is what i am sending from UI
{"Pager.RowsPerPage":"1","Pager.CurrentPage":"2","StartDate":"2021-11-08T17:25:21.243Z"}
I've tried to create the Pager object on ReportViewModel constructor but no luck.
What can be the issue?
Thanks.
CodePudding user response:
It should be like this
<button id="submitForm">Submit</button>
@section scripts {
<script type="text/javascript">
var formData = '{ "DateRange": "2021/11/08", "Pager": { "CurrentPage": 2 } }';
var options = {
url: '/Home/Report',
type: 'POST',
dataType: 'json',
data: JSON.parse(formData)
}
$('#submitForm').click(function () {
$.ajax(options)
.done(function (response) {
console.log('response: ', response);
});
});
</script>
}
and then in the controller
[HttpPost]
public ActionResult Report(ReportViewModel report)
{
var dateRange = report.DateRange;
var page = report.Pager.CurrentPage;
return Json("{ submited = true }", JsonRequestBehavior.AllowGet);
}
public class ReportViewModel
{
public string DateRange { get; set; }
public Pager Pager { get; set; }
}
public class Pager
{
public int CurrentPage { get; set; }
}