I have the get and post methods for my create View in my controller. When i run this, it gives me an error: {“Object reference not set to an instance of an object.”} The rest of the code is the create get and post methods.. Does anyone pehaps know what i could be doing wrong?
// GET: /Title/Create
public ActionResult Create()
{
var model = new title
{
create_dt = DateTime.Now,
last_maint_dt = DateTime.Now,
row_version = 1,
status = "ACTIVE",
user_id = currentUser.UserName,
last_user_id = currentUser.UserName
};
return View(model);
}
// POST: /Title/Create
[HttpPost]
public ActionResult Create(title title)
{
if (ModelState.IsValid)
{
db.titles.Add(title);
db.SaveChanges();
return RedirectToAction("Index");
}
if (Request.IsAuthenticated)
{
currentUser = Membership.GetUser(false);
if (currentUser != null)
{
userid = (Guid)currentUser.ProviderUserKey;
}
}
var model = new title
{
create_dt = DateTime.Now,
last_maint_dt = DateTime.Now,
row_version = 1,
status = "ACTIVE",
user_id = currentUser.UserName,
last_user_id = currentUser.UserName
};
return View(model);
}
You’re conditionally calling
Membership.GetUserand clearly expecting that it can return null… and if the request isn’t authenticated you’re not even assigning a value tocurrentUser. However, you’re then fetchingcurrentUser.UserNametwice when constructing the model. That will obviously fail ifcurrentUseris null.Really, you should look at the stack trace of the exception – that should show you where things are going wrong.