Question

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?

Was it helpful?

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; }
}

OTHER TIPS

A model binder only binds submitted values. It does not bind values rendered in the view.

You need to create a custom EditorTemplate to render the tags as you need them.

MVC can already bind to a List, I would recommend using the built in technology that already does what you need.

I didn't notice any code about adding the binder, did you add your ModelBinder to the Binders?

protected void Application_Start()
{
  ModelBinders.Binders.Add(typeof(IList<Tag>), new TagListModelBinder());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top