If I need to retrieve an object from a custom model binder should the binder interact with the service layer, the repository layer, or …?

纵然是瞬间 提交于 2019-12-06 06:07:30

问题


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; }
}

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"

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.

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));

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?


回答1:


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.



来源:https://stackoverflow.com/questions/1119928/if-i-need-to-retrieve-an-object-from-a-custom-model-binder-should-the-binder-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!