Custom Model Binding In ASP.NET Core MVC Pattern

banner

Introduction

In the MVC pattern, Model binding maps the HTTP request data to the parameters of a Controllers action method. The parameter can be of a simple type like integers, strings, double, etc. or they may be complex types. MVC then binds the request data to the action parameter by using the parameter name.

Model binder provides a mapping between the request data and the application model. The default model binder which is provided by ASP.NET Core MVC supports most of the common data types and would also meet most of our needs. The built-in model binding functionality can be extended by implementing a custom model binder which transform the input prior to binding it to a model.

Solution

For creating a custom model binder class, we have to inherit from IModelBinder interface. This interface has an async method named "BindModelAsync" and it has a parameter of type ModelBindingContext. The ModelBindingContext class provides the context that model on which the binder acts.

Using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Threading.Tasks; namespace ModelBinder.ModelBinder { public class CustomModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { throw new NotImplementedException(); } } }

Example

Let us implement a custom model binder that can convert incoming request data which is passed as query string to a user defined class. The request data is the one which contains all model properties separated with pipe (|) and even our custom model binder and it will separate the data and assign them to the repspective model property.

Steps involved in creating a custom model binder.

First step

namespace ModelBinder { using Microsoft.AspNetCore.Mvc.ModelBinding; using ModelBinder.Model; using System; using System.Threading.Tasks; public class CustomModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); var values = bindingContext.ValueProvider.GetValue("Value"); if (values.Length == 0) return Task.CompletedTask; var splitData = values.FirstValue.Split(new char[] { '|' }); if (splitData.Length >= 2) { var result = new User { Id = Convert.ToInt32(splitData[0]), Name = splitData[1] }; bindingContext.Result = ModelBindingResult.Success(result); } return Task.CompletedTask; } } }

Once the model is created using the request data, we then have to assign this model to Result property of the binding context using ModelBindingResult.Success method. This method represents model binding operation was successful. Same as the Success Method, It has also a method name “Failed” it represent a fail model binding operation.

Interesting in building a custom-built model binder?

Our experts can give a Master Class and measuring incoming request data. Aegis Softtech developers have experience and knowledge to help you with this critical service.

Now, the next step is to register a Model binder. We have two ways to register Model binder:

  1. Using the ModelBinder attribute
  2. By defining model binder provider and then register it in startup class

Register custom model binder using ModelBinder Attribute

We can apply a custom model binder using ModelBinder attribute by defining attributes on an action method or model. Whenever we are using this method that is applying attribute on action method, we need to define this attribute on every action method which we want use this custom binding on. Also, we can apply this attribute on model it-self.

Applying the ModelBinder Attribute on a Model

namespace ModelBinder.Model { using Microsoft.AspNetCore.Mvc; [ModelBinder(BinderType = typeof(CustomModelBinder))] public class User { public int Id { get; set; } public string Address { get; set; } public string Name { get; set; } } }

Applying ModelBinding Attribute on Action method

[HttpGet] [Route("test")] public IActionResult Index([ModelBinder(BinderType = typeof(CustomModelBinder))]User u) { return View(); }

Register custom Model binder in startup class

Also, we can register our custom model binder in a startup class which will then be available for all action methods. To register a custom model binder, we have to create a binder provider. This model binder provider class implements an interface called IModelBinderProvider interface. The built-in model binders, it should be noted that, have also have their own model binder providers. We can also specify the type of arguments model binder produces, not the input of our model binder. In following example, provider works just with "CustomModelBinder".

Custom Model binder provider

namespace ModelBinder { using Microsoft.AspNetCore.Mvc.ModelBinding; using ModelBinder.Model; public class CustomModelBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context.Metadata.ModelType == typeof(User)) return new CustomModelBinder(); return null; } } }

Now, we have to add this provider to MVC model binder provider collection.Then we can add custom model binder provider to MVC model binder collection. i.e. in the ConfigureServices methods of the Startup class.

public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc( config => config.ModelBinderProviders.Insert(0, new CustomModelBinderProvider()) ); }

Output

custom-model

In the above example, we are receiving the required data from the request (query-string). In the same way, we can also get the data from request body. With the post method, we need to post the data within request body. In the following example, I have read the request body data and converted it in to required form-data.

Model Binder

namespace ModelBinder { using Microsoft.AspNetCore.Mvc.ModelBinding; using ModelBinder.Model; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Threading.Tasks; public class CustomModelBinder1 : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); string valueFromBody = string.Empty; using (var sr = new StreamReader(bindingContext.HttpContext.Request.Body)) { valueFromBody = sr.ReadToEnd(); } if (string.IsNullOrEmpty(valueFromBody)) { return Task.CompletedTask; } string values = Convert.ToString(((JValue)JObject.Parse(valueFromBody)["value"]).Value); var splitData = values.Split(new char[] { '|' }); if (splitData.Length >= 2) { var result = new User1 { Id = Convert.ToInt32(splitData[0]), Name = splitData[1] }; bindingContext.Result = ModelBindingResult.Success(result); } return Task.CompletedTask; } } }

Output

custom-model

Impact

With Customer binders, we can get data whose properties are not primitive. This gives us a better control of the data and thus helps us in some scenarios.

Conclusion

ASP.NET Core has many built-in model binders and their providers that meet our most all needs. But custom model binder provides a way to bind our data which is in specific format to our model classes or action parameter.

.Net developers India have shared this to understand the concept of Custom Model Binding in ASP.NET Core pattern and its use in MVC based application development.

Related article

Designing website applications which meet the MVC (Model-View-Controller) project design was tough to be executed along the ASP.NET.

What features Telerik UI brings for Asp.Net MVC web development community will be discussed by experts in this article.

For many years, developers who used Unit Testing were dissatisfied with the many issues they encountered when attempting to apply automated testing to ASP.NET sites, particularly those that were created using the WebForms technology (which was, for many, a synonym of ASP.NET).

DMCA Logo do not copy