-1

I am creating an MVC application.I am getting an error of Null Reference Exception on change password form functionality.

My Model class code

public partial class tblUser
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Please Enter Your Email Id")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Please Enter Your Password")]
    [DataType(DataType.Password)]
    [StringLength(18, ErrorMessage = "The password must be atleast 3 characters long", MinimumLength = 3)]
    public string Password { get; set; }

    [Required(ErrorMessage = "Please Enter Your Password")]
    [DataType(DataType.Password)]
    [StringLength(18, ErrorMessage = "The password must be atleast 3 characters long", MinimumLength = 3)]
    public string NewPassword { get; set; }
}

My view(Changepassword.cshtml)

@model MvcWebApplication1.Models.tblUser

<div class="container">
    <div class="row rowspace1">
        <div class="col-sm-12">
            @Html.ActionLink("Log Out", "Login", "Home")
        </div>
    </div>
    <div class="row">
        <div id="CpassTitle">
            <h3>CHANGE PASSWORD</h3>
        </div>
        @using (Html.BeginForm("Changepassword", "Home", FormMethod.Post))
        {
            
                <table class="center">
                    <tr>
                        <td>Old Password</td>
                        <td>
                            @Html.EditorFor(pass => pass.Password)
                        </td>
                        <td>@Html.ValidationMessageFor(pass => pass.Password)</td>
                    </tr>
                    <tr class="rowspace">
                        <td>New Password</td>

                        <td>
                            @Html.EditorFor(pass => pass.NewPassword)
                        </td>
                        <td>@Html.ValidationMessageFor(pass => pass.NewPassword)</td>
                    </tr>
                  
                    <tr class="rowspace">
                        <td colspan="3" id="button">
                            <input type="submit" value="Change Password" /></td>
                    </tr>
                    <tr class="rowspace"><td colspan="3">@ViewBag.Message</td></tr>
                </table>
            
        }

    </div>
</div> 

When I click on change password submit button I am getting a NullReferenceException in action method on line userDetail.Password = login.NewPassword;

[HttpPost]
public ActionResult Changepassword(tblUser login)
{
    UserDetailsEntities db = new UserDetailsEntities();
    var detail = db.tblUsers.Where(log => log.Password == login.Password).FirstOrDefault();
    if (detail != null)
    {
        var userDetail = db.tblUsers.FirstOrDefault(c => c.Email == login.Email);
        userDetail.Password = login.NewPassword;
        
        db.SaveChanges();
        ViewBag.Message = "Record Inserted Successfully!";
    }
    else
    {
        ViewBag.Message = "Password not Updated!";
    }
    return View(login);
}
Community
  • 1
  • 1
Aman Mehta
  • 29
  • 1
  • 10
  • 1
    Make sure `userDetail` object is not null before updating the Password property value. – Shyju Apr 30 '16 at 19:07
  • Your `FirstOrDefault` method is probably returning null when it finds no record for the email passed. – Will Ray Apr 30 '16 at 19:07
  • @Will SO should I remove **FirstorDefault** Method. – Aman Mehta Apr 30 '16 at 19:09
  • No. Just add a null check before accessing the properties (`if(userDetail!=null) { \\update password here }`). But you should find out why it is giving you no result. May be your `login.Email` does not have a valid email address which you have in your db table. Put a breakpoint and inspect the variable values. – Shyju Apr 30 '16 at 19:10
  • Yeah, what @Shyju said. Also, your view does not have a `HiddenFor` for the `Email` property of the model, so it will always be null in your HttpPost method and presumably is causing all this. – Will Ray Apr 30 '16 at 19:12
  • I have used HiddenFor for the email property of model in my view.But still it is not working. I have also tried the code . – Aman Mehta Apr 30 '16 at 19:27
  • Show us your stack trace. But the fix for a `NullReferenceException` is always the same: *find the null object that is being dereferenced,* and fix your code so that it is no longer null, or it's no longer being dereferenced while it is null. – Robert Harvey Apr 30 '16 at 19:28
  • @Shyju Yes you were right.I added the null check and then I checked by putting a breakpoint my login.Email is returning null. but the email id in my db table is correct. The email id in my db table is Id - 1 Email - mehta.aman850@gmail.com Password - aman – Aman Mehta Apr 30 '16 at 20:06

2 Answers2

-1
[HttpPost]
public ActionResult Changepassword(tblUser login)
{
    UserDetailsEntities db = new UserDetailsEntities();
    var detail = db.tblUsers.Where(log => log.Password == login.Password).FirstOrDefault();

    // ADDED NULL CHECK HERE
    if (detail != null)
    {
        var userDetail = db.tblUsers.FirstOrDefault(c => c.Email == login.Email);
         if(userDetail !=null)
         {
              userDetail.Password = login.NewPassword;

              db.SaveChanges();
              ViewBag.Message = "Record Inserted Successfully!";
         }
    }
    else
    {
        ViewBag.Message = "Password not Updated!";
    }
    return View(login);
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
suulisin
  • 1,414
  • 1
  • 10
  • 17
-1

Check ur db. It's either closing before you read from it or it's connecting to some other table.

Munam Yousuf
  • 431
  • 1
  • 6
  • 17