开发者

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

开发者 https://www.devze.com 2023-01-11 14:07 出处:网络
I\'ve been struggling for this for an hour and I don\'t understand why there\'s a problem. I have an abstract class

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 { 开发者_如何学Pythonget { 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.


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.


Where are you creating the instance variable DB?

model.DB = DB

Where is the right DB getting initialized?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号