0

I have tried simple user log in using asp.net mvc4. I have used this condition (ModelState.IsValid), It was workiing before two days. Now i am trying to execute this program, But that property is terminating the condition. Please anyone help me to rectify this problem. This is my controller code {

[HttpPost]
        [AllowAnonymous]
        public ActionResult LogIn(Project.Models.Tbl_Users user)
        {
            int userid = user.UserID;
            var sessionid = Session["userid"];
            Session["RoleId"] = user.RoleId;
            Session["Username"] = user.UserName;
            var sessionval = Session["Username"].ToString();
            if (!ModelState.IsValid)
            {
                if (Isvalid(user.UserName, user.UserPassword))
                {
                    var db = new Project.Models.EntitiesContext();
                    var userroleid = db.Tbl_Users.FirstOrDefault(u => u.UserName == user.UserName);


                    Session["RoleId"] = userroleid.RoleId;
                    int sessionroleid = Convert.ToInt32(Session["RoleId"]);

                    FormsAuthentication.SetAuthCookie(user.UserName, false);

                    string sessionusername = Session["Username"].ToString();
                    if (sessionroleid == 1)
                    {

                        return RedirectToAction("adminpage", "LogIn");
                    }
                    else
                        if(sessionroleid==2)
                        {
                            return RedirectToAction("teammanager", "LogIn");
                        }
                        else
                    {
                        return RedirectToAction("userpage", "LogIn");
                    }

                }
                return View(sessionval);
            }
            return View();
        }








    private bool Isvalid(string username, string password)
                {
                    bool Isvalid = false;
                    using(var db = new Project.Models.EntitiesContext())
                    {
                        var user = db.Tbl_Users.FirstOrDefault(u => u.UserName == username);
                        var pass = db.Tbl_Users.FirstOrDefault(u => u.UserPassword == password);
                        if (username != null)
                        {
                            try
                            {
                                if (user.UserName == username)
                                {
                                    if (pass.UserPassword == password)
                                    {
                                        Isvalid = true;
                                        //Session["RoleId"] = user.RoleId;
                                        //int sessionid = Convert.ToInt32(Session["RoleId"]);
                                    }
                                }
                            }
                            catch
                            {
                                //Response.Write("Login Failed For The User");
                                Isvalid = false;
                            }

                        }

                    }

} This is my model {

 [Required(ErrorMessage = "User Name is Invalid")]
    [StringLength(200)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Password Field is Invalid")]
    [StringLength(50, MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string UserPassword { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }

}

This is my view code {

<form method="post" id="signin" action="@Url.Action("LogIn", "LogIn")">

<body style="background-color: Gray;">
    <div>
         <div>
         </div>
        @if (!Request.IsAuthenticated) 
        {
         <strong>@Html.Encode(User.Identity.Name)</strong>
        @Html.ActionLink("Log Out", "LogOut", "LogIn")
        } 
        else 
        {
        <fieldset>
            <div>@Html.LabelFor(u => u.UserName)</div>
            <div>@Html.TextBoxFor(u => u.UserName)

            @if (Request.IsAuthenticated)
            {
                @Html.ValidationMessageFor(u => u.UserName)
                @*@Html Session["Username"] = @Html.TextBoxFor(u => u.UserName);*@
            }
            </div>
            <div>@Html.LabelFor(u => u.UserPassword)</div>
            <div>@Html.PasswordFor(u => u.UserPassword)
                @Html.ValidationMessageFor(u => u.UserPassword)
            </div>
            <div>@Html.CheckBoxFor(u => u.RememberMe)
                @Html.LabelFor(u => u.RememberMe, new { @class = "checkbox" })
            </div>
            <div>
             @Html.ValidationSummary(true, "Login Failed")
            </div>
            <input type="submit" value="LogIn"/>
        </fieldset>
        }
    </div>
</body>
</form>

}

Vetri
  • 77
  • 2
  • 3
  • 10
  • where you are facing actual problem..does your method `Isvalid` always return false – Nilesh Gajare Feb 19 '14 at 11:30
  • before i have used this condition if (ModelState.IsValid), It was entered into the control,, Now i am using this same condition it is not working, Condition is terminating now. when i use like this (!ModelState.IsValid), It is entering into the condition, I dont know why it is not working..pls help me out – Vetri Feb 19 '14 at 11:42
  • Condition is failing bcoz your model is not valid... – Nilesh Gajare Feb 19 '14 at 11:47
  • How to find the model is valid or not?. I didn't changed anything, but now condition is failing. How to change the model is valid. Is there any property to change it? – Vetri Feb 19 '14 at 11:54
  • property `Model.IsValid` checks whether your posted model is valid or not so while posting data make sure your model is valid i.e all conditions are met – Nilesh Gajare Feb 19 '14 at 11:56
  • Show me your model and view i'll tell you the conditions required – Nilesh Gajare Feb 19 '14 at 11:56
  • I have updated my post with codes for model and view..pls check it out – Vetri Feb 19 '14 at 12:06
  • and what are the values you are posting i.e Your `username` must be less than 200 and your password should be inbetween 6 to 20 characters then only your model will be valid else it will be invalid – Nilesh Gajare Feb 19 '14 at 12:12
  • I am following this condition, it also not working. Whether its necessary to use this condition for project?. If we don't use it, it will cause any problem? – Vetri Feb 19 '14 at 12:19
  • If you remove then you have to do client validation to make sure passed model is Valid ...main purpose of `Model.IsValid` is to check whether passed model is valid or not – Nilesh Gajare Feb 19 '14 at 12:25
  • @Nilesh i will try to solve this problem. Thank you very much for your valuable time with me. – Vetri Feb 19 '14 at 12:30

1 Answers1

0

please DEBUG your code.

past this code below, just above if(!ModelState.IsValid)

var propertiesWithErrors = ModelState.Where(state => state.Value.Errors.Any()).Select(state => state.Key);;

propertiesWithErrors will give you the list of properties that has validation errors.

Amila
  • 3,711
  • 3
  • 26
  • 42