MVC Ajax POST 不绑定子对象
MVC Ajax POST does not bind subobject
我有一个控制器
[HttpPost]
public async Task<IActionResult> Report([FromBody][FromForm] ReportViewModel request)
{
var x = request.StartDate; // binds data
var y = request.Pager.RowsPerPage; // always NULL
}
ReportViewModel 是
public class ReportViewModel : IEntity, IResponse
{
public string DateRange { get; set; }
public Pager Pager { get; set; }
}
public class Pager
{
public int CurrentPage { get; set; }
}
我正在使用 AJAX 调用控制器,这是我从 UI
发送的内容
{"Pager.RowsPerPage":"1","Pager.CurrentPage":"2","StartDate":"2021-11-08T17:25:21.243Z"}
我尝试在 ReportViewModel 构造函数上创建 Pager 对象,但没有成功。
可能是什么问题?
谢谢。
应该是这样的
<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>
}
然后在控制器中
[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; }
}
我有一个控制器
[HttpPost]
public async Task<IActionResult> Report([FromBody][FromForm] ReportViewModel request)
{
var x = request.StartDate; // binds data
var y = request.Pager.RowsPerPage; // always NULL
}
ReportViewModel 是
public class ReportViewModel : IEntity, IResponse
{
public string DateRange { get; set; }
public Pager Pager { get; set; }
}
public class Pager
{
public int CurrentPage { get; set; }
}
我正在使用 AJAX 调用控制器,这是我从 UI
发送的内容{"Pager.RowsPerPage":"1","Pager.CurrentPage":"2","StartDate":"2021-11-08T17:25:21.243Z"}
我尝试在 ReportViewModel 构造函数上创建 Pager 对象,但没有成功。
可能是什么问题?
谢谢。
应该是这样的
<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>
}
然后在控制器中
[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; }
}