我正在尝试将视图模型与嵌套视图模型的动态列表绑定。我想出了如何绑定嵌套的 1 个视图模型。但是我如何绑定它们的列表呢?
我的课程:
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 秒。我的模型比这复杂得多,但我隐藏了大部分。我读过使用自定义模型绑定器可以提高响应时间。