Alex
Alex

Reputation: 36161

C#/ASP.NET MVC: I set the property's value, but it's still null

I've been struggling for this for an hour and I don't understand why there's a problem.

I have an abstract class

public abstract class IValidated
{
    public bool IsValid { get { return (GetRuleViolation() == null); } }

    public abstract RuleViolation GetRuleViolation();

}

And a validation class

public class RegisterModel : IValidated
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }


    public MyDataContext DB { get; set; }

    // ....
}

When I use the validation, I get an error

public ActionResult Register(RegisterModel model)
{
        model.DB = DB;

        if (model.IsValid) // an exception here

}

DB is null! I need to pass the datacontext object to the validation to check if the e-mail is unique and stuff like that.

Here's how the DB is initialized:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    DB = new MyDataContext();
} 

The DB property is set in the Register method, I debugged that. But in the IsValid method of the class it's null...

UPDATE

Looks like the MVC framework for some reason runs the IsValid method before the Register ActionResult (and before the DB object is initialized). I think it's because it's doing all "magic" stuff with passing the RegisterModel parameters to the view. So I just put

if (DB != null)

and it helped.

Apparently, the IsValid method is run again when I call it, and the DB object is not null by then.

UPDATE 2

Since IsValid was a property, ASP.NET MVC was binding it, after turning it into a method, the problem disappeared.

Upvotes: 0

Views: 545

Answers (2)

48klocs
48klocs

Reputation: 6113

You may want to rename IValidated to ValidationBase or something - the I prefix denotes an interface rather than a base class.

Is DB being set up in your controller's constructor? I'm guessing it's not, which leads to the Register method assigning a null reference to model.DB which leads to your NullReferenceException.

Also, MVC2 will read properties during databinding to try to validate them. That's probably what's biting you. If you change IsValid from a property to a method, the problem will go away.

Upvotes: 2

Dismissile
Dismissile

Reputation: 33071

Where are you creating the instance variable DB?

model.DB = DB

Where is the right DB getting initialized?

Upvotes: 1

Related Questions