How i can pass data to controller in ajax using asp MVC

This question is an exact duplicate of:

I have login form can user write username and password and i check if the username right or not i'm try to send the username to Home controller by ajax that's my controller code

          [HttpPost]
       public JsonResult ValidateUser(string username,string password)
    {
        using(var contxt=new EnglisCenterEntities())
        {
            var data = from a in contxt.Employee
                       where a.Username == username && a.Passwords == password
                       select a.EmpName;
            string Empname = data.FirstOrDefault();
            if(data.Count()>0)
            {

                return Json(new { Success = true } ,JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
            }
        }
    }

and this is my ajax code

     <script>
        $(document).ready(function () {

               $('#savedata').click(function (e) {
                           e.preventDefault();
                           var data = {
                               username: function () { return $("#username").val(); },
                               password: function () { return $("#password").val(); }

                           };

                           $.ajax({
                               url: "/Account/validateuser",
                               type: "POST",
                               data: data,
                               dataType: "json",

                               success: function (response) {





                                       window.location.href = "@Url.Action("Index", "Home")";

                                   }
                                   else
                                       notifyBar();
                                       @*window.location.href = "@Url.Action("Login", "Account")";*@
                               },

                               error: function () {
                                   console.log('Login Fail!!!');
                               }
                           });
                       });
});

this code check if the user exist or not and it's working but i want to send the user name with redirect the Index action. How i can do that?

Answers 1

  • you can use this code

    var xsrf = 'username=' + username + '&password='+password;
    $.ajax({
        url: "/Account/validateuser",
        type: "POST",
        data: xsrf ,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }...
    

    `


Related Articles