Search code examples
asp.netviewmodelmodelbindersmulti-selectupdatemodel

asp.net mvc strongly typed view model with multiselect


I would like to know how i can bind my form values to my strongly typed view from a MultiSelect box.

Obviously when the form submits the multi-select box will submit a delittemered string of my values selected...what is the best way to convert this string of values back into a list of objects to attach to my model to be updated?

public class MyViewModel {
    public List<Genre> GenreList {get; set;}
    public List<string> Genres { get; set; }
}

When updating my model inside the controller i am using UpdateModel like below:

Account accountToUpdate = userSession.GetCurrentUser();
UpdateModel(accountToUpdate);

However i need to somehow get the values from the string back into objects.

I beleive it may have something to do with model-binders but i can't find any good clear examples of how to do this.

Thanks!! Paul


Solution

  • You're correct that a model binder is the way to go. Try this...

    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    [ModelBinder(typeof(MyViewModelBinder))]
    public class MyViewModel {
        ....
    }
    
    public class MyViewModelBinder : DefaultModelBinder {
        protected override void SetProperty(ControllerContext context, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) {
            if (propertyDescriptor.Name == "Genres") {
                var arrVals = ((string[])value)[0].Split(',');
                base.SetProperty(context, bindingContext, propertyDescriptor, new List<string>(arrVals));
            }
            else
                base.SetProperty(context, bindingContext, propertyDescriptor, value);
        }
    }