Reputation: 7752
I am currently working in asp.net mvc4. And implementing user profile information. My controller I-e HomeController contain;
public ActionResult Resume()
{
using (ProfileInfo profile = new ProfileInfo())
{
return View(profile.ProfileGetInfoForCurrentUser());
}
}
My profileinfo class contains a method wich return type 'ResumeViewModel';
public ResumeViewModel ProfileGetInfoForCurrentUser()
{
ProfileBase profile = ProfileBase.Create(Membership.GetUser().UserName);
ResumeViewModel resume = new ResumeViewModel();
resume.Email = Membership.GetUser().Email.ToString();
resume.FullName = Membership.GetUser().UserName;
return resume;
}
Now my ResumeViewModel looks like this;
public class ResumeViewModel
{
public string FullName { get; set; }
public string Email { get; set; }
}
While my view is strongly type of '@model PortfolioMVC4.Models.ResumeViewModel'
. However, when I run this I get the following error;
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
{
Line 14: ProfileBase profile = ProfileBase.Create(Membership.GetUser().UserName);
Line 15: ResumeViewModel resume = new ResumeViewModel();
Line 16: resume.Email = Membership.GetUser().Email.ToString();
Line 17: resume.FullName = Membership.GetUser().UserName;
I am getting error on line 15; which is basically code that exist in ProfileGetInfoForCurrentUser method (as shown above). I don't know what to do? Any help regard to this is apreciatable;
Upvotes: 0
Views: 5934
Reputation: 124794
Possibly Membership.GetUser()
has returned null - is the client authenticated?
Maybe you need to put an [Authorize]
attribute on your controller.
The debugger is your friend!
Upvotes: 2
Reputation: 1039498
It looks like the Email property is null, so you cannot call the .ToString
method on it. And by the way the MembershipUser.Email
property is already a string, so calling a .ToString()
on it very hardly makes any sense.
Also I would recommend you calling the Membership.GetUser()
method only once and caching the result into a local variable to avoid hammering your database with multiple requests:
public ResumeViewModel ProfileGetInfoForCurrentUser()
{
var user = Membership.GetUser();
ProfileBase profile = ProfileBase.Create(user.UserName);
ResumeViewModel resume = new ResumeViewModel();
resume.Email = user.Email;
resume.FullName = user.UserName;
return resume;
}
And by the way you seem to be declaring some profile
variable without doing lots of useful things with it. Are you sure it's really necessary?
Upvotes: 4