how can i call web api Controller from ajax

丶灬走出姿态 提交于 2019-12-10 14:23:42

问题


I am a beginner of ASP MVC with web api.

By using below codes I tried to call a function which is written at the controller. For checking I used breakpoint so the control could not go to the controller so that I can not track actually what is going on.

The given code explains how to pass username and password to the controller:

<script type="text/javascript">
function Login() {
var Login = {};
Login.username = document.getElementById("txtUserName").value;
Login.password = document.getElementById("txtPassword").value;
$.ajax({

URL: 'api/Login/' + Login,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(Login),
success: function (data) {

alert("Saved successfully");
}
})
}
</script>

This is the controller which i used to pass

public class LoginController : ApiController
{
[HttpPost]
public void  Login(Login  login)
{
string user = login.UserName.ToString();
string password = login.Password.ToString();
}

}

回答1:


Basically it's a case sensitivity problem on URL vs url combined with some unnecessary work. So change your script to:

<script type="text/javascript">
    function Login() {

      var Login = {};
      Login.username = $("#txtUserName").val();
      Login.password = $("#txtPassword").val();

      $.ajax({
         url: '/api/Login/',
         method: 'POST',
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         data: Login,
         success: function (data) {
          alert("Saved successfully");
         },
        fail : function( jqXHR, textStatus ) {
          alert( "Request failed: " + textStatus );
        }
     })
  }
</script>


来源:https://stackoverflow.com/questions/29137486/how-can-i-call-web-api-controller-from-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!