I have an ASP.net MVC Core 2 (can upgrade to 3 if required) web app.
There are several different classes, landlord, tenant, contractor - they each have an address object, and other different properties.
I have a partial view that is passed the address object from each view.
<partial name="_AddressPartial" , model="@Model" />
This works fine. But when the form is posted, each address field is posted flat, as the names of the address are things like "Street", not "Address.Street" - because the address model is passed to the partial. So the model binder is looking for "Street" etc, not as part of an Address object.
I could pass the object from each page the partial is on, and prefix "Address." to each field name, but Landlord, Contractor, Tenant etc are all different classes so I'd need a different partial per page which defeats the point.
I might be able to use a base class with Address, then derive all the other classes from that, and bind the base class to the partial? But that seems like overkill just to get a partial working.
I could flatten the Address object into each ViewModel - this would create significantly more work when writing to the database though (you can't just pass Dapper an Address model, you'll have to manually write some SQL for the update), and create lots of repetition.
How can I re-use a partial between all the pages, keep it DRY, and avoid the listed problems.
I've googled it and the above is all I could find. Am I missing something?
To fix it, you can try following approaches.
Approach 1: set HtmlFieldPrefix with
"Address"in_AddressPartial.cshtmlas below.Approach 2: implement a custom model binder to bind data to
Streetetc properties.Address class
Custom model binder
AddressBinderApply it to
AddresspropertyTest and Result
For approach 1:
For approach 2: