开发者

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 mode开发者_Python百科l-binders but i can't find any good clear examples of how to do this.

Thanks!! Paul


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜