Fixing the Model Binding issue of ASP.NET MVC 4 and ASP.NET Web API
- by imran_ku07
Introduction:
Yesterday when I was checking ASP.NET forums, I found an important issue/bug in ASP.NET MVC 4 and ASP.NET Web API. The issue is present in System.Web.PrefixContainer class which is used by both ASP.NET MVC and ASP.NET Web API assembly. The details of this issue is available in this thread. This bug can be a breaking change for you if you upgraded your application to ASP.NET MVC 4 and your application model properties using the convention available in the above thread. So, I have created a package which will fix this issue both in ASP.NET MVC and ASP.NET Web API. In this article, I will show you how to use this package.
Description:
Create or open an ASP.NET MVC 4 project and install ImranB.ModelBindingFix NuGet package.
Then, add this using statement on your global.asax.cs file,
using ImranB.ModelBindingFix;
Then, just add this line in Application_Start method,
Fixer.FixModelBindingIssue();
// For fixing only in MVC call this
//Fixer.FixMvcModelBindingIssue();
// For fixing only in Web API call this
//Fixer.FixWebApiModelBindingIssue();
.
This line will fix the model binding issue. If you are using Html.Action or Html.RenderAction then you should use Html.FixedAction or Html.FixedRenderAction instead to avoid this bug(make sure to reference ImranB.ModelBindingFix.SystemWebMvc namespace). If you are using FormDataCollection.ReadAs extension method then you should use FormDataCollection.FixedReadAs instead to avoid this bug(make sure to reference ImranB.ModelBindingFix.SystemWebHttp namespace). The source code of this package is available at github.
Summary:
There is a small but important issue/bug in ASP.NET MVC 4. In this article, I showed you how to fix this issue/bug by using a package. Hopefully you will enjoy this article too.