Visual Studio 2022 - Issues with Razor Pages Not Recognizing Custom Model Binder in ASP.NET Core 6
I'm maintaining legacy code that I keep running into I've searched everywhere and can't find a clear answer... I'm currently facing a frustrating issue with my ASP.NET Core 6 application where my custom model binder isn't being recognized in my Razor Pages. I've implemented a custom model binder for a complex type `Product`, but when I submit the form, it always returns null instead of binding the data correctly. Hereβs a brief overview of my `Product` class: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } ``` I've created a custom model binder that looks like this: ```csharp public class ProductModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { var name = bindingContext.ValueProvider.GetValue("Name").FirstValue; var priceValue = bindingContext.ValueProvider.GetValue("Price").FirstValue; decimal price; if (!decimal.TryParse(priceValue, out price)) { bindingContext.ModelState.AddModelError("Price", "Invalid price format."); return Task.CompletedTask; } var product = new Product { Name = name, Price = price }; bindingContext.Result = ModelBindingResult.Success(product); return Task.CompletedTask; } } ``` And I registered it in `Startup.cs` like this: ```csharp services.AddControllersWithViews(options => { options.ModelBinderProviders.Insert(0, new ProductModelBinderProvider()); }); ``` In my Razor Page, I have: ```csharp public class CreateModel : PageModel { [BindProperty] public Product Product { get; set; } public void OnGet() { } public IActionResult OnPost() { if (!ModelState.IsValid) { return Page(); } // Save product to database return RedirectToPage("Success"); } } ``` When I hit the submit button from my form, the `Product` model is always null. I've checked the names of the input fields in my Razor Page, and they match the properties of the `Product` class. Here's how the form looks: ```html <form method="post"> <input type="text" name="Name" /> <input type="text" name="Price" /> <button type="submit">Submit</button> </form> ``` I've tried several things like ensuring that the input names match the property names, checking the order of model binder registration, and even simplifying the model binder logic to just bind a string, but nothing seems to work. Has anyone encountered a similar issue or have any suggestions on how to resolve this? Thanks in advance! For context: I'm using Csharp on macOS. Is this even possible? What's the correct way to implement this?