我想我可以在闲逛之后回答我自己的问题。
在我的 ViewModel 中,我使用字符串数组作为数据类型,如下所示:
public class ProfilePageViewModel : PageViewModel
{
[Required(ErrorMessage = "*")]
public string[] FavGenres { get; set; }
public IDictionary<int, string> GenresList { get; set; }
}
在我看来,我可以将选定的值设置为 FavGenres,然后我有一个自定义模型绑定器来将逗号分隔的字符串再次转换为有效对象......如果你想知道这里是我的自定义模型绑定器完整......
public class AccountCustomModelBinder : DefaultModelBinder
{
private readonly IGenreRepository genreRepository;
private readonly ITimezoneRepository timeZoneRepository;
private readonly ICountryRepository countryRepository;
public AccountCustomModelBinder() : this(
ServiceLocator.Current.GetInstance<IGenreRepository>(),
ServiceLocator.Current.GetInstance<ITimezoneRepository>(),
ServiceLocator.Current.GetInstance<ICountryRepository>())
{
}
public AccountCustomModelBinder(IGenreRepository genreRepository, ITimezoneRepository timeZoneRepository,
ICountryRepository countryRepository)
{
Check.Require(genreRepository != null, "genreRepository is null");
Check.Require(timeZoneRepository != null, "timeZoneRepository is null");
Check.Require(countryRepository != null, "countryRepository is null");
this.genreRepository = genreRepository;
this.timeZoneRepository = timeZoneRepository;
this.countryRepository = countryRepository;
}
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
Account account = bindingContext.Model as Account;
if (account != null)
{
// gender
if (propertyDescriptor.Name == "Gender")
{
if (bindingContext.ValueProvider.ContainsKey("Gender"))
{
account.Gender = bindingContext.ValueProvider["Gender"].AttemptedValue.ToString();
return;
}
}
// TimezoneId
if (propertyDescriptor.Name == "TimezoneId")
{
if (bindingContext.ValueProvider.ContainsKey("TimezoneId")) {
account.Timezone = timeZoneRepository.FindOne(Convert.ToInt32(bindingContext.ValueProvider["TimezoneId"].AttemptedValue));
return;
}
}
// CountryId
if (propertyDescriptor.Name == "CountryId")
{
if (bindingContext.ValueProvider.ContainsKey("CountryId")) {
account.Country = countryRepository.FindOne(Convert.ToInt32(bindingContext.ValueProvider["CountryId"].AttemptedValue));
return;
}
}
// FavGenres
if (propertyDescriptor.Name == "FavGenres")
{
if (bindingContext.ValueProvider.ContainsKey("FavGenres")) {
// remove all existing entries so we can add our newly selected ones
account.ClearFavGenres();
string favIds = bindingContext.ValueProvider["FavGenres"].AttemptedValue;
foreach (string gId in favIds.Split(',')) {
account.AddFavGenre(genreRepository.Get(Convert.ToInt32(gId)));
}
return;
}
}
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}