我想要有一个视图,用户可以在集合中添加项目而无需转到新的视图(该场景是一种用户添加有关工作经验,技能等信息的简历站点,以及去一个新的视图添加每个小东西似乎是荒谬的)。添加到EntityCollection添加到实体框架中的集合的末尾?
所以我有一个编辑视图,显示了已添加项目的文本框数量,并且如果用户添加项目,则会有一个ajax调用来访问新鲜收集的方法。
这里是有问题的方法:
public ActionResult Edit(int id)
{
Consultant consultant = _repository.GetConsultant(id);
var vm = GetViewModel(consultant);
return View(vm);
}
private DetailsViewModel GetViewModel(Consultant consultant)
{
return new DetailsViewModel
{
Programs = consultant.Programs.ToList(),
Consultant = consultant
};
}
public ActionResult NewProgram(int id)
{
//TODO: ordering is rather strange, because the entitycollection adds at the beginning rather than the end...
Consultant consultant = _repository.GetConsultant(id);
consultant.Programs.Add(new Program());
_repository.Save();
var vm = GetViewModel(consultant);
return PartialView("ProgramList", vm);
}
我们的问题是:当NewProgram方法被调用,它增加了一个新的方案,以顾问的对象,并创建一个新的视图模型送回去,但它将新程序添加到EntityCollection的开头,而不是最后。但是,当您发布完整的表单并且再次打开编辑视图时,该列表会将新添加的程序放在最后。这很奇怪。用户会认为他/她在列表的开头添加了一个项目,但是如果他们再次返回页面,他们会在最后找到新项目。
为什么会这样做,并且有什么方法可以让NewProgram()直接在最后添加新程序?
如果有人认为“他应该使用ViewModel”与DTOs,而不是直接与EF对象工作,那么我已经在这条道路上停留了一段时间(Entity Framework and MVC 3: The relationship could not be changed because one or more of the foreign-key properties is non-nullable),到目前为止没有人已经明确告诉我如何实现这一点,并且仍然能够在同一视图中添加和删除项目。在维护集合的索引方面存在问题,或者实体框架不会让我保存......而且代码变成了一场噩梦。
这样,我至少有理解的代码,唯一的事情是我需要有这种添加在“正常”的顺序进行,即添加在收藏的结束......
任何想法?
BTW:
这工作,但似乎非常必要,首先必须将新程序添加到咨询对象,而新方案创建视图模型,然后将其单独添加到视图模型...
public ActionResult NewProgram(int id)
{
//TODO: ordering is rather strange, because the entitycollection adds at the beginning rather than the end...
Consultant consultant = _repository.GetConsultant(id);
var vm = GetViewModel(consultant);
var program = new Program();
consultant.Programs.Add(program);
_repository.Save();
vm.Programs.Add(program);
return PartialView("ProgramList", vm);
}
那么,后者实际上工作,虽然它似乎是一个相当随意的事情......但是,谢谢,无论如何这是一个更好的。 – Anders 2011-03-01 11:13:51
@安德斯·斯文森:我希望这种方式行不通。如果您在视图中指定程序的顺序,例如按升序ID对它们进行排序,则可以避免此“破解”。 – 2011-03-01 11:26:49