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 code 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.
I need the bind to UDFDsSelected
in the call back for my project to work.
_UDFDSelected.cshtml
:
@using Data.Models;
@model FilterReport;
@{
var serializedUDFDs = Newtonsoft.Json.JsonConvert.SerializeObject(Model.UDFDsSelected?.Select(udfd => new { udfd.Code, udfd.Description }).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:
Found a Work Around:
`// 1) In the model, I add a string version of the complex object:`
public string uDFDsSelectedString { get; set; }
public List<UDFD> uDFDsSelected { get; set; }
`// 2) In the view, serialize the complex object to the string version:
// and imbed it in the post back through a hidden field.`
var serializedUDFDs = Newtonsoft.Json.JsonConvert.SerializeObject(Model.uDFDsSelected?.Select(udid => new { udfd.Code, udfd.Description }).ToList());
<input type="hidden" name="FilterReport.uDFDsSelectedString" value="@serializedUDFDs" />
`// 3) In the post back, deserialize the string version back into the complex object:`
string json = FilterReport.uDFDsSelectedString;
List <UDFD> udids = Newtonsoft.Json.JsonConvert.DeserializeObject<List<UDFD>>(json);