我正在尝试使用嵌套视图模型的动态列表绑定viewmodel。我想出了如何绑定嵌套的1个viewmodel。但是如何绑定它们的列表呢?
我的课程:
public class PracticeViewModel
{
public List<OpeningHourViewModel> OpeningHours { get; set; }
}
public class OpeningHourViewModel
{
public OpeningHourViewModel()
{
Id = Guid.NewGuid();
From1 = DateTime.Today;
From2 = DateTime.Today;
From3 = DateTime.Today;
To1 = DateTime.Today;
To2 = DateTime.Today;
To3 = DateTime.Today;
}
[HiddenInput(DisplayValue = false)]
[Browsable(false)]
public Guid Id { get; set; }
public DayOfWeek DayOfWeek { get; set; }
[Display(Name = "From", ResourceType = typeof(Resources))]
public DateTime From1 { get; set; }
[DateGreaterThanAttribute("From1")]
[Display(Name = "To", ResourceType = typeof(Resources))]
public DateTime To1 { get; set; }
[Display(Name = "From", ResourceType = typeof(Resources))]
public DateTime From2 { get; set; }
[Display(Name = "To", ResourceType = typeof(Resources))]
[DateGreaterThanAttribute("From2")]
public DateTime To2 { get; set; }
[Display(Name = "From", ResourceType = typeof(Resources))]
public DateTime From3 { get; set; }
[Display(Name = "To", ResourceType = typeof(Resources))]
[DateGreaterThanAttribute("From3")]
public DateTime To3 { get; set; }
public HourSchedule HourSchedule { get; set; }
public bool HasMorningOpening
{
get
{
return From1.TimeOfDay != new TimeSpan() &&
To1.TimeOfDay != new TimeSpan();
}
}
public bool HasAfternoonOpening
{
get
{
return From2.TimeOfDay != new TimeSpan() &&
To2.TimeOfDay != new TimeSpan();
}
}
public bool HasEveningOpening
{
get
{
return From3.TimeOfDay != new TimeSpan() &&
To3.TimeOfDay != new TimeSpan();
}
}
我的模型绑定器(到目前为止):
public class PractieModelBinder : IModelBinder
{
private readonly IPracticeService _practiceService;
public PracticeModelBinder(IPracticeService practiceService)
{
_practiceService = practiceService;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var id = (Guid)controllerContext.RouteData.Values["Id"];
var viewModel = Map.This(_practiceService.GetPractice(id)).To<PracticeViewModel>();
return viewModel;
}
private T TryGet<T>(ModelBindingContext bindingContext, string key) where T : class
{
if (String.IsNullOrEmpty(key))
return null;
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + key);
if (valueResult == null && bindingContext.FallbackToEmptyPrefix)
valueResult = bindingContext.ValueProvider.GetValue(key);
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueResult);
if (valueResult == null)
return null;
try
{
return (Nullable<T>)valueResult.ConvertTo(typeof(T));
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
return null;
}
}
}
提前致谢,
编辑:
使用默认模型绑定器和客户端验证来验证我的模型需要10秒钟。我的模型比这复杂得多,但我隐藏了大部分内容。我已经读过使用自定义模型绑定器可以缩短响应时间。