Posts

Showing posts with the label model-binding

Specify equality comparer for model binding to collection types

Image
Clash Royale CLAN TAG #URR8PPP Specify equality comparer for model binding to collection types I have an API where you can specify a list of names to get. Duplicate names are not allowed and if two names differ only by casing then they are considered duplicates. GET /api/people?names=john&names=alice In my own .NET code I would gather all these names in a HashSet with a custom equality comparer. HashSet var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase); But I don't think ASP.NET Core model binding is flexible enough for that. // GET /api/people?names=john&names=JOHN [HttpGet("api/people")] public GetPeople([FromQuery] HashSet<string> names) { // this works but names contains both john and JOHN } What do I have to change so that the names set only contains john and not JOHN? names 2 Answers 2 You can use a List<string> in the method heade...

Custom Model Binder Provider always null .net core

Image
Clash Royale CLAN TAG #URR8PPP Custom Model Binder Provider always null .net core I'm having a problem trying to get custom model binders to work as a query parameter like I have gotten to work previously in .net framework 4.7. To ensure this wasn't a scenario where my object was too complex, I reduced the model to a simple string but even then I cannot get this to work. I have a simple model I would like to be binded from query parameters. public class SearchModel { public string SearchTerms { get; set; } } And I have configured the ModelBinder and ModelBinderProvider as shown here like so. public class TestModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(SearchModel)) { throw new ArgumentException($"Invalid binding context supplied {bindingContext.ModelType}"); } var model = (SearchModel)bindingContext.Model ?? new SearchModel(); va...

ASP.NET Core 2.1 MVC - Model Binding - Dropdown List Value

Image
Clash Royale CLAN TAG #URR8PPP ASP.NET Core 2.1 MVC - Model Binding - Dropdown List Value I have a ViewModel something like this which contains two properties. UserSelectedState - String value ListOfStateNames - This is a List of SelectListItem. I am able to bind the model to the View and the user sees the list of state names and makes one selection. I am posting it back to the controller and I am able to see the "UserSelectedState" value assigned correctly. But, the "ListofStateNames" is empty in the Model when posted back. Just trying to understand why it should be empty. Since it's the same Model which is populating the list items in the View. Any explanation on why it is empty ? 1 Answer 1 This is just how html POST works. On a roundtrip only values of certain types are returned: input, hidden field, selected option. Where readonly fields, labels, etc. are not returned. S...