0

UserController.cs

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Customers customer)
        {
            if (ModelState.IsValid)
            {
                    var obj = db.Customers.Where(a => a.Username.Equals(customer.Username) && a.Password.Equals(customer.Password)).FirstOrDefault();
                    if (obj != null)
                    {
                        Session["IC"] = obj.IC.ToString();
                        Session["Username"] = obj.Username.ToString();
                        return RedirectToAction("AfterLogin");
                    }
            }
            return View(customer);
        }

        public ActionResult AfterLogin()
        {
            if (Session["IC"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Login");
            }
        }

Login.cshtml

@model LeafLife.Models.Customers
@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2>Login</h2>

@using (Html.BeginForm("Login", "User", FormMethod.Post))
{
    <fieldset>
        <legend>Mvc Simple Login Application Demo</legend>

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        @if (@ViewBag.Message != null)
        {
            <div style="border: 1px solid red">
                @ViewBag.Message
            </div>
        }
        <table>
            <tr>
                <td>@Html.LabelFor(a => a.Username)</td>
                <td>@Html.TextBoxFor(a => a.Username)</td>
                <td>@Html.ValidationMessageFor(a => a.Username)</td>
            </tr>
            <tr>
                <td>@Html.LabelFor(a => a.Password)</td>
                <td>@Html.PasswordFor(a => a.Password)</td>
                <td>@Html.ValidationMessageFor(a => a.Password)</td>
            </tr>
            <tr>
                <td><input type="submit" value="Login" /></td>
            </tr>
        </table>
    </fieldset>
}  

Customers.cs

public class Customers
    {
        [Key]
        public int IC { get; set; }
        [Display(Name = "Username")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Username required")]
        public string Username { get; set; }
        [Display(Name = "First Name")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "First name required")]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Last name required")]
        public string LastName { get; set; }

        [Display(Name = "Email Address")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Email Address required")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [Display(Name = "Date of birth")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime DateofBirth { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Password is required")]
        [DataType(DataType.Password)]
        [MinLength(6, ErrorMessage = "Minimum 6 characters required")]
        public string Password { get; set; }

        [Display(Name = "Confirm Password")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Confirm password and password do not match")]
        public string ConfirmPassword { get; set; }
        //ForeignKey
        public int MembershipTypesId { get; set; }

        [ForeignKey("MembershipTypesId")]
        public MembershipTypes MembershipTypes { get; set; }
        

    }

I tested it, after i inserted the required field it just stuck on the login page. The google chrome did pop out the save password notification only once after many test. I test it again in incognito mode is won't login just displaying the Login page. I tried again on Chrome and it was the same again.

  • I don't know how this kind of authentication work, but if this was the regular type of authentication, the issue would be you're not passing the authorization middleware to the pipeline. To do so, add `app.UseAuthorization()` in the configure method of startup.cs – Qudus Aug 11 '20 at 12:55
  • Have you debugged the application? Create breakpoints to see if `ModelState.IsValid` is true and if `obj` is not null. – Andy Refuerzo Aug 11 '20 at 14:12
  • But i am using no authentication, so there is not startup.cs in it. Should I change it into individual authentication so that i can use the function ? –  Aug 12 '20 at 01:06
  • @AndyRefuerzo The ``ModelState.IsValid`` returned false, im sure that theres is not typo within the coding. –  Aug 19 '20 at 02:23
  • Kindly post the code for `LeafLife.Models.Customers`. If `ModelState.IsValid` is returning false, it means that some required properties of the `LeafLife.Models.Customers` is not passing the validation. – Andy Refuerzo Aug 19 '20 at 02:45

1 Answers1

0

As mentioned in the comments, ModelState.IsValid returns false which means that some properties of LeafLife.Models.Customers is not passing the model validation.

The reason you are "stuck" in the login page is because the HttpPost version of the Login() method looks like this after evaluation:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(Customers customer)
    {
        if (ModelState.IsValid) // value is false so skip this block
        {
            // code here is not executed
        }

        return View(customer); // this shows the Login view
    }

It just returns the Login view. You need to find the root cause as to why ModelState.IsValid is returning false. Look into ModelState.Values and dig through the collection for any model errors.

Here's a good article explaining ModelState and model validation.

EDIT: Now that the code for Customer model has been added, I would suggest to use View Models instead of directly using data models in views. Here are some good questions to point you in the right direction:

What is ViewModel in MVC?

What is difference between Model and ViewModel in asp.net core mvc?

Andy Refuerzo
  • 3,312
  • 1
  • 31
  • 38
  • So i had read the article, I have around 5 field and 3 of them is empty so that's why the ``ModelState`` is returning false.Am I right about it. So in another words that the ``ModelState`` is not suitable to use in this action? –  Aug 19 '20 at 12:23
  • 5 fields are marked `[Required]` but 3 are empty and it is correctly being flagged as having an invalid state. The usage of `ModelState` is correct, the only issue is the model that you are checking. The approach of using your data model `Customer` directly in a view should be improved by using View Models. I'll update my answer to include links to questions about View Models to point you in the right direction. – Andy Refuerzo Aug 19 '20 at 13:22
  • I get it now, thanks for your sharing and help.((Sorry for the late reply –  Aug 23 '20 at 02:08