当我在View中显示testplanViewModel列表并且用户选择一个时,SelectedTestplanId将返回到Controller post动作。还应该返回的是属于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; }
}
OpenTestplanViewModel
@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));
答案 0 :(得分:1)
HTML并没有真正起作用。如果您希望从下拉列表的帖子返回多个值(帮助程序生成select
元素),您必须在视图模型上创建一个属性,然后在控制器中进行解析。 / p>
例如,如果您有两个整数ID
字段,则组合属性可以创建类似23_42
的值。然后,您可以使用Split
方法获取正确的值(23
&amp; 42
)。