Search code examples
asp.net-mvcasp.net-mvc-3model-bindingimodelbinder

ASP.NET MVC3 Custom Model Binder Issues


I have an applicant model that contains a list of tags:

public class Applicant
{
    public virtual IList<Tag> Tags { get; protected set; }
}

When the form is submitted, there is an input field that contains a comma-delimited list of tags the user has input. I have a custom model binder to convert this list to a collection:

public class TagListModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var incomingData = bindingContext.ValueProvider.GetValue("tags").AttemptedValue;
        IList<Tag> tags = incomingData.Split(',').Select(data => new Tag { TagName = data.Trim() }).ToList();
        return tags;
    }
}

However, when my model is populated and passed into the controller action on POST, the Tags property is still an empty list. Any idea why it isn't populating the list correctly?


Solution

  • The problem is you have the protected set accessor in Tags property. If you change that into public as below things will work fine.

    public class Applicant
    {
        public virtual IList<Tag> Tags { get; set; }
    }