0

I am using repository Pattern. When I login, I get the error :

"Object reference not set to an instance of an object."

Everything is perfect but i don't know why this error is showing Can anybody tell me where I'm wrong. LoginViewModel and user Model are same and i am using database first approach.

Login Page

  public ActionResult Login(LoginViewModel loginModel )
        {
            try
            {
                if (!string.IsNullOrEmpty(loginModel.Username) && !string.IsNullOrEmpty(loginModel.Password))
                {
                    var Username = loginModel.Username;
                    var Password = loginModel.Password;

                    var result = _IUserRepository.ValidUser(Username, Password);
                    if (result.id==0 || result.id < 0)
                    {
                        ViewBag.errormessage = "Enter Invalid Username and Password";

                    }
                    else
                    {
                        return RedirectToAction("Index");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return View();
        }

UserRepository

  public class UserRepository : IUserRepository
        {
            private dbContext _context;
            public UserRepository(dbContext context)
            {
                this._context = context;
            }
            public bool UpdatePassword(user user)
            {
                throw new NotImplementedException();
            }

            public user ValidUser(string username, string passWord)
            {
                try
                {
                    var validate = (from user in _context.users
                                    where user.Username == username && user.Password == passWord
                                    select user).SingleOrDefault();
                    return validate;
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
        }

IUserRepository

 public interface IUserRepository
    {
        user ValidUser(string username, string password);
        bool UpdatePassword(user user);

    }

LoginViewModel

 public class LoginViewModel
    {

        public int id { get; set; }

        [Required(ErrorMessage ="Username is Required")]
        public string Username { get; set; }
        [Required(ErrorMessage = "Password is Required")]
        public string Password { get; set; }
    }

Login.chtml

@model RepositoryPattren.Models.LoginViewModel

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>LoginViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
hello
  • 13
  • 5
  • Can you add the full stack trace so that we know where the error occurs? – Jb31 Oct 20 '19 at 17:19
  • Without concrete stack trace it is impossible to define whats going on on your code – So_oP Oct 20 '19 at 17:29
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – haldo Oct 20 '19 at 18:15
  • This line returns null: `_IUserRepository.ValidUser(Username, Password);`. May you try adding `ToList` here: `from user in _context.users.ToList()`? and debug ValidUser method. – A. Nadjar Oct 21 '19 at 05:22
  • Your are returning `SingleOrDefault` from `ValidUser` function. If its invalid user this will return null and in `Login` method you are accessing id of user without checking for null. – ghulam_ali Oct 21 '19 at 07:01
  • i have added more code you see more clear . – hello Oct 21 '19 at 08:03
  • @ghulam_ali yes you are right this line return null , i have change as you suggest me still return null. – hello Oct 21 '19 at 08:06

1 Answers1

0

Try to check these situations in your code: 1 - check to ensure that login model which you received isn't null 2- Are you Registered IUserRepository dependency? if you didn't register, the instance isn't injected 3- You are using SingleOrDefault then if the condition doesn't match it will return null for the default value, and you didn't check for null so do like below code:

if (result!=null && result.id==0 || result.id < 0)
                    {
                        ViewBag.errormessage = "Enter Invalid Username and Password";

                    }
                    else
                    {
                        return RedirectToAction("Index");
                    }
  • i have comment some line that why iuserRepository dependency not working. thanks for pleasure time. – hello Oct 21 '19 at 15:55