Search code examples
asp.net-mvcmodel-bindingimodelbinder

Custom IModelBinder and Database Access


For a user object in my asp.net mvc project, I have written a custom modelbinder to check whether passwords are valid and whether two matching passwords were entered etc..

The login name needs to be unique though, I was wondering whether I can check for that in the modelbinder, or is this considered bad practise ?

The thing is that the binder is called before you even get to the controller, so I would have two instances of my dataContext floating around and thus multiple connections to the database, I guess I could set up a factory of sorts for that.

This is a code snippet of what I do now in the controller:

// POST: /Users/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Users user)
{            
    myDataContext db = new myDataContext();

    if (!ViewData.ModelState.IsValid)
    {                
        return View(user);
    }            

    Users testUser = db.Users.SingleOrDefault(p => p.LoginNaam == user.LoginNaam);
    if (testUser != null) { //Error stuff here }
}

Solution

  • I would not check the username availability in the model binder. I think it's the CreateUser method's job to do that in this case.

    So the action would be like this :

    // POST: /Users/Create
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Users user)
    {            
        myDataContext db = new myDataContext();
    
        if (!ViewData.ModelState.IsValid)
        {                
            return View(user);
        }
    
        try {
            db.CreateUser(User);
        }
        catch (ArgumentException e) {
            ModelState.AddModelError(e.ParamName, e.Message);
            return View(user);
        }
        return View("UserCreated", user)
    }