我如何从Ajax调用Web API控制器 [英] how can i call web api Controller from ajax
本文介绍了我如何从Ajax调用Web API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是使用Web API的ASP MVC的初学者.
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();
}
}
推荐答案
基本上,这是URL
与url
区分大小写的问题,结合了一些不必要的工作.因此,将脚本更改为:
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>
这篇关于我如何从Ajax调用Web API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文