I have changed a little the Polymorphic binding example from this article.
- Add
[Required]attribute to theCPUIndexandScreenSizeproperties ofLaptoprespectivelySmartPhoneclasses. - Run example and create whatever kind of device without filling in CPU index nor Screen size.
- It runs correctly - model is bound and validated (shows you the error, that "CPU index / Screen size are required".
So far ok.
Now add new class:
public class DeviceWrapper
{
public Device Device { get; set; }
}
and modify the AddDevice.cshtml.cs file:
...
[BindProperty]
public DeviceWrapper Device { get; set; } // model type changed here
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
switch (Device.Device) // added Device. prefix to respect new model structure
{
case Laptop laptop:
Message = $"You added a Laptop with a CPU Index of {laptop.CPUIndex}.";
break;
case SmartPhone smartPhone:
Message = $"You added a SmartPhone with a Screen Size of {smartPhone.ScreenSize}.";
break;
}
return RedirectToPage("/Index");
}
Modify also the page AddDevice.cshtml to respect new model structure. I.e. prefix every Device.{prop} with Device. in all name attributes. Example:
<select id="Device_Kind" name="Device.Device.Kind" asp-items="Model.DeviceKinds" class="form-control"></select>
Now run the application. Put breakpoint into the AddDeviceModel.OnPost method. Do the same as in the first example - create device without filling neither CPU index nor Screen size. Check the value of ModelState.IsValid which is now true. Model is bound, but not validated. What should I do to apply validation also for this wrapped model.
Try it out on my fork of sample: https://github.com/zoka-cz/AspNetCore.Docs/tree/master/aspnetcore/mvc/advanced/custom-model-binding/3.0sample/PolymorphicModelBinding
