2016-04-03 42 views
0

我有登录表单可以用户写用户名和密码,我检查用户名是否正确或我没有尝试发送用户名到主控制器通过ajax这是我的控制器代码我怎么可以传递数据到控制器在Ajax使用MVC

  [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); 
      } 
     } 
    } 

,如果用户存在或不和它的工作,但我想用发送重定向指数操作的用户名,这是我的Ajax代码

 <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!!!'); 
           } 
          }); 
         }); 
}); 

此代码检查。我该怎么做?

+0

:'用户名:函数(){/ * * /}',而不是实际价值? – dotnetom

+0

我曾经使用过用户名:$(“#username”)。val(),但它不起作用。在我更改为这种方法后变成了工作 –

+0

在你提出这个问题之前两次,你接受了错误的答案。当你想重定向时使用ajax发布是毫无意义的。 –

回答

0

在你Url.Action你可以给额外的数据:

@Url.Action("Index", "Home", new { Name = "yourUserName" }) 
0

确保数据阿贾克斯(键,值)对发送。这些键是一样的(区分大小写)

听到我秀,你是发送键:用户名和你控制器接收:用户名

$(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!!!'); 
          } 
         }); 
        }); 

});

1

你可以用你为什么要使用此功能,该代码

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

`

相关问题