Inject a dependency into a custom model binder and using InRequestScope using Ninject

The ModelBinders are reused by MVC for multiple requests. This means they have a longer lifecycle than request scope and therefore aren’t allowed to depend on objects with the shorter request scope life cycle. Use a Factory instead to create the IPostRepository for every execution of BindModel

How to use a DI / IoC container with the model binder in ASP.NET MVC 2+?

A couple of observations: Don’t inject dependencies just to query them in the constructor There’s no reason to inject an ITimeProvider into a user just to invoke Now immediately. Just inject the creation time directly instead: public User(DateTime creationTime) { this.CreationTime = creationTime; } A really good rule of thumb related to DI is that … Read more

Custom model binder for a property

override BindProperty and if the property is “PropertyB” bind the property with my custom binder That’s a good solution, though instead of checking “is PropertyB” you better check for your own custom attributes that define property-level binders, like [PropertyBinder(typeof(PropertyBBinder))] public IList<int> PropertyB {get; set;} You can see an example of BindProperty override here.

ASP.NET MVC A potentially dangerous Request.Form value was detected from the client when using a custom modelbinder

You have a few options. On the model add this attribute to each property that you need to allow HTML – best choice using System.Web.Mvc; [AllowHtml] public string SomeProperty { get; set; } On the controller action add this attribute to allow all HTML [ValidateInput(false)] public ActionResult SomeAction(MyViewModel myViewModel) Brute force in web.config – definitely … Read more

Custom DateTime model binder in Asp.net MVC

you can change the default model binder to use the user culture using IModelBinder public class DateTimeBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value); return value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture); } } public class NullableDateTimeBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); … Read more