我使用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的列表,這樣我可以重新使用一次發佈的值...但是我希望有人有一個更優雅的方式處理這個問題。
謝謝!
保羅