Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm doing a login page in mvc4 .

I did till now:

Successfully login with post back.

But i need :

Successfully login without post back using ajax and jQuery


Here is my code :
index.cshtml


HTML
<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<script language="javascript">
    function ValidateUser() {
        var userid = $("#<%=txtuserid.ClientID %>").attr('value');
        var password = $("#<%=txtpassword.ClientID %>").attr('value');
        $("#btnSubmit").attr({ 'value': 'Please wait...' });
        $.ajax({
            url: "Home/Index",
            type: "POST",
            cache: false,
            success: function (html) {
                if (html == "1") {
                    alert("Successfull login.");
                } else {
                    alert("Wrong User Id and Password.");
                }

                $("#btnSubmit").attr({ 'value': 'Submit' });
                return false;
            }
        });
    }
</script>




@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "ID" }))
{
@Html.AntiForgeryToken() // this is for prevent CSRF attack
@Html.ValidationSummary(true)
if (@ViewBag.Message != null)
{

@ViewBag.Message

}

Login

@Html.LabelFor(m => m.EmailId)


@Html.TextBoxFor(m => m.EmailId, new { id = "txtuserid" })
@Html.ValidationMessageFor(m => m.EmailId)


@Html.LabelFor(m => m.Password)


@Html.TextBoxFor(m => m.Password, new { id = "txtpassword" })
@Html.ValidationMessageFor(m => m.Password)


<input type="submit" value="Submit" id="btnlogin" onclick="javascript:return ValidateUser();" />



}




HomeController.cs


C#
[HttpPost]
      [ValidateAntiForgeryToken]
       public ActionResult Index(LoginMVC u)
       {

           if (ModelState.IsValid) // this is check validity
           {
               using (LoginAndSignUpEntities dc = new LoginAndSignUpEntities())
               {
                   var v = dc.tbl_Detailstbl.Where(a => a.Email_Id.Equals(u.EmailId) && a.Password.Equals(u.Password)).FirstOrDefault();
                   if (v != null)
                   {
                       Session["LogedUserID"] = v.Email_Id.ToString();
                       Session["LogedUserFullname"] = v.Name.ToString();
                       return RedirectToAction("AfterLogin");
                   }
               }
           }
           return View(u);
       }
      public ActionResult AfterLogin()
      {
          if (Session["LogedUserID"] != null)
          {
              return View();
          }
          else
          {
              return RedirectToAction("Index");
          }
      }




Please help me.....
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900