6

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

Glen Solsberry
  • 11,960
  • 15
  • 69
  • 94
Paul Hinett
  • 1,951
  • 2
  • 26
  • 40

2 Answers2

3

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);
    }
}
Jasel
  • 535
  • 8
  • 14
Nick Patterson
  • 934
  • 8
  • 11
0

Check out Phil Haacks blog post on the subject. I used that as the basis for a multi select strongly typed view in a recent project.

Antony Scott
  • 21,690
  • 12
  • 62
  • 94