我使用DataAnnotations进行错误检查,在我的asp.net mvc应用程序中,我也使用强类型的ViewModels。asp.net mvc multiselect回覆后记住状态
我的错误检查工作正常,并回传到我的观点与错误消息,如果一个字段为空。不过,我的表单上有一个MultiSelect/Listbox,我需要记住错误发生后的状态。
此刻我的视图模型看起来像这样(我只包括相关属性):
public class ProfilePageViewModel : PageViewModel
{
public IList<FavouriteGenreViewModel> FavGenres { get; set; }
[Required(ErrorMessage = "*")]
public string SelectedGenres { get; set; }
public IDictionary<int, string> GenresList { get; set; }
}
这是我在我的控制器操作:
public ActionResult Profile(ProfilePageViewModel viewModel)
{
if(!ModelState.IsValid)
{
viewModel.CountriesList = dropDownTasks.GetCountries();
viewModel.GendersList = dropDownTasks.GetGenders();
viewModel.GenresList = dropDownTasks.GetGenres();
viewModel.TimezonesList = dropDownTasks.GetTimezones();
viewModel.FavGenres =
return View(viewModel);
}
. . .
我多选需要FavouriteGenreViewModel的列表要选择GenresList中的选项,它会在GET操作中使用AutoMapper执行此操作,但显然我无法在帖子中使用AutoMapper,因为它会忘记我发布的值。
我想过使用ID的逗号分隔字符串而不是FavouriteGenreViewModel的列表,这样我可以重新使用一次发布的值...但是我希望有人有一个更优雅的方式处理这个问题。
谢谢!
保罗