当我在我的视图中显示 testplanViewModels 列表并且用户选择一个时,SelectedTestplanId 将返回到控制器发布操作。还应该返回属于 SelectedTestplanId 的 TemplateId。
当 AutoMapper 定义运行时,Testplan.TestplanId被隐式复制到TestplanViewModel.TestplanId。同样可以通过在 TestplanViewModel 上提供TemplateId来完成。当用户现在在视图中选择“TestplanViewModel”时,如何将 TemplateId 附加到控制器操作以在那里访问它?DropDownList 不允许 2 个 dataValueFields!
CreateMap<Testplan, TestplanViewModel>().ForMember(dest => dest.Name, opt => opt.MapFrom(src => string.Format("{0}-{1}-{2}-{3}", src.Release.Name, src.Template.Name, src.CreatedAt, src.CreatedBy)));
public ActionResult OpenTestplanViewModels()
{
IEnumerable<Testplan> testplans = _testplanDataProvider.GetTestplans();
var viewModel = new OpenTestplanViewModel
{
DisplayList = Mapper.Map<IEnumerable<Testplan>, IEnumerable<TestplanViewModel>>(testplans)
};
return PartialView(viewModel);
}
public class TestplanViewModel
{
public int TestplanId { get; set; }
public string Name { get; set; }
}
public class OpenTestplanViewModel
{
[Required(ErrorMessage = "No item selected.")]
public int SelectedTestplanId { get; set; }
public IEnumerable<TestplanViewModel> DisplayList { get; set; }
}
开放测试计划视图模型
@using (Html.BeginForm("Open", "Testplan"))
{
@Html.ValidationSummary(false)
@Html.DropDownListFor(x => x.SelectedTestplanId, new SelectList(Model.DisplayList, "TestplanId", "Name"), new { @class = "listviewmodel" })
}
解决方案:
public class OpenTestplanViewModel
{
[Required(ErrorMessage = "No item selected.")]
public string TestplanIdAndTemplateId { get; set; }
public IEnumerable<TestplanViewModel> DisplayList { get; set; }
public int SelectedTestplanId
{
get
{
return Convert.ToInt32(TestplanIdAndTemplateId.Split(new[] { '_' }).First());
}
}
public int SelectedTemplateId
{
get
{
return Convert.ToInt32(TestplanIdAndTemplateId.Split(new[] { '_' }).Last());
}
}
}
CreateMap<Testplan, TestplanViewModel>()
.ForMember(d => d.Name, o => o.MapFrom(src => string.Format("{0}-{1}-{2}-{3}", src.Release.Name, src.Template.Name, src.CreatedAt, src.CreatedBy)))
.ForMember(d => d.TestplanIdAndTemplateId, o => o.MapFrom(src => src.TestplanId + "_" + src.TemplateId));