问题描述
如果我有一个类似的类:
If I have a class similar to this:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public Pet myPet { get; set; }
}
当我创建一个自定义的模型绑定,从我的表格后不会在宠物被发送,它会发出像这样的数据:姓:myFirstName名字:myLastNamemyPet:myPetsName
When I create a custom model binder, the Post from my form will not be sending in a Pet, it would send in data like this: firstName: "myFirstName" lastName: "myLastName" myPet: "myPetsName"
由于宠物的名字传递,而不是实际的Pet对象,需要从模型绑定内恢复宠物的对象。
Since the Pet's name is passed in, and not the actual Pet object, the Pet object needs to be retrieved from within the model binder.
我的问题是,如果模型绑定与服务层,存储库层的互动,还是应该甚至可以检索的宠物?与服务层的问题是,我似乎没有能够获得的ModelState时初始化服务:((this.ModelState)给我一个错误)
My question is, should the model binder be interacting with the Service Layer, the Repository Layer, or should it even be retrieving the Pet? The problem with the Service Layer is that I don't seem to have access to ModelState when initializing the service: ((this.ModelState) gives me an error)
_petService = new PetService(new ModelStateWrapper(this.ModelState));
如果我需要的模型绑定创建一个Person对象,那么宠物将需要以某种方式分配...我怎么做呢?
If I need the model binder to create a Person object, then the Pet would need to be assigned somehow... how am I supposed to do this?
谢谢,
马特
Thanks,
Matt
推荐答案
我做的是什么,而不是使用绑定到业务对象的视图/ presentation模式。请记住,您的用户可能输入无效值,您将需要促使他们改正自己的错误时,重新显示这些无效值给用户。但是,你的真实的业务对象可能不会接受无效值。因此视图模型必须允许任何用户输入,甚至输入业务对象也不会接受。
What I do is use a view/presentation model instead of binding to business objects. Remember that your users might enter invalid values, and you will need to re-display these invalid values to the user when prompting them to correct their mistakes. But your "real" business objects probably won't accept invalid values. So the view model must allow for any user input, even input the business objects won't accept.
这使得绑定容易。你并不需要打一个仓库绑定,更新与(有效)用户输入的业务对象,只有当。
This makes the binding easy. You don't need to hit a repository to bind, only when updating the business object with (valid) user input.
这篇关于如果我需要检索自定义模型粘合剂的对象应该粘结剂与服务层,存储库层或互动......? Asp.Net MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!