0

I want to query the user that log in success in the web site :

This is what I did in my views :

var query = from i in Model.DataContext.Customers
            where i.WebAccount == User.Identity.Name
            select i;

But it show the error Object reference not set to an instance of an object, I have no idea , why it is like that. Any one know about that? Thanks.

2 Answers 2

2

There are a couple issues to discuss.

  1. You should not be querying your database from the View. Logic remains in the Controller.
  2. You likely never set the DataContext property on your view model. The message stating that the "object reference not set to an instance of an object" pertains to a NullReferenceException which means you're attempting acces on a null value.
  3. See #1 again, it's important.
Sign up to request clarification or add additional context in comments.

1 Comment

So what can I avoid to do that in my view?
1

socheata,

there's a very good chance that your User.Identity object could be null if the user has not yet signed in (thus the User.Identity.Name invocation would throw an error).

So, there are several approaches that spring to mind:

  • move that logic out of the view and into either your service layer or your controller action

  • create an html helper that provides the functionality that you require from the view. useful if this is required across multiple views

there are of course other options, but these would be my starting point.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.