Is there a way to BindProperty
on a complex type in ASP.NET Core and MVVM?
I’m having a problem binding back data from what a user selected on a webpage back to the callback method. Simple data types bind back correctly.
However I have a list of objects that do not bind. In the view, I added to to serialize the data of interest, added it to a hidden field, and can see in the debugger that it is included as apart of the post.
However, only the Code
field of class UDFD
is included and the Description
field is not. I only need the code info but it’s failing to bind to UDFDsSelected
in the call back.
_UDFDSelected.cshtml
:
@using Data.Models;
@model FilterReport;
@{
var serializedUDFDs = Newtonsoft.Json.JsonConvert.SerializeObject(Model.UDFDsSelected?.Select(UDFD => UDFD.Code).ToList());
}
<input type="hidden" name="FilterReport.UDFDsSelected" id="UDFDsSelectedHidden" value="@serializedUDFDs" />
jQuery:
var formData = $('#frmReport').serializeArray();
$.post('/reports/AddUDFD',
formData
).done(function (response)
Reports.cshtml.cs
:
[BindProperty]
public FilterReport FilterReport { get; set; }
#region Public
public IActionResult OnPostAddUDFD(string UDFD, string description)
{
// Do Work
return new PartialViewResult
{
ViewName = "_UDFDList",
ViewData = new ViewDataDictionary<FilterReport>(ViewData, FilterReport)
};
}
FilterReport.cs
:
public class FilterReport
{
public string TimeZone { get; set; } = string.Empty;
public List<UDFD> UDFDsSelected { get; set; }
}
UDFD.cs
:
public class UDFD
{
public string Code { get; set; }
public string? Description { get; set; }
}
Debugger on serialized postback data: