简体   繁体   中英

How do I add to modelstate in my library?

In my DB class I have a function like this:

        //Check if the user login exists in the DB if this is a new user. 
        if ((userModelItem.UserId == 0) || (userModelItem.UserId == null))
        {
            if (_db.ABUsers.Count(s => s.Loggin1 == user.Loggin1 || s.Loggin1 == user.Loggin2 ||
                s.Loggin2 == user.Loggin1 || s.Loggin2 == user.Loggin2) > 0)
            {
                var exLog = new ExceptionThrowHandler();
                exLog.SaveNewException("SaveUserModelItem", "ABUserRepository", "Loggin1 or loggin2 exists in DB");
                return null;

Is it possible to here also try and add an error to the modelstate without having to pass the modestate as an object to the function? IE can I get hold of the modestate from httpcontext.current or something?

IE can I get hold of the modestate from httpcontext.current or something?

Although you could use something like System.Web.HttpContext I would strongly recommend against it . Using an environment value like this would make your code impossible to test through unit testing.

Your best bet is to either pass the context value down to the class or return something so that the appropriate layer access the HTTP context.

Hard to give much advice without knowing where you're trying to call this function from as this affects what might be available to you. As far as I know it's not possible to access ModelState from HttpContext.Current though knowing more about your circumstance might help find another work around.

Without knowing more the best I could suggest would be a helper function at an intermediate layer that does take modelstate and then calls your DB function, tests the result to see if it needs to affect the modelstate, and then returns the original response.

Why not throw an exception from the data access layer, catch it in the calling controller, and update the modelstate there? This seems like a much cleaner separation of concerns to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM