asp.net mvc strongly typed view model with multiselect
Asked Answered
A

2

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

Anele answered 5/1, 2010 at 21:56 Comment(0)
R
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);
    }
}
Richel answered 15/12, 2010 at 16:33 Comment(0)
O
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.

Octans answered 15/12, 2010 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.