【发布时间】:2017-01-18 13:32:22
【问题描述】:
我是 asp.net core、c# 和 MVC 6 的新手。我正在尝试通过 ajax 将数据发送到我的控制器。
function ajaxMethodData() {
$.ajax({
url: "AjaxWithData", // hard coded for testing
type: "POST",
data: JSON.stringify({ username: "NeXT405" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
},
error: function () {
alert('error');
}
});
}
控制器中的方法如下所示。该方法被 ajax 请求调用。
[HttpPost]
public IActionResult AjaxWithData([FromBody] string username )
{
Debug.WriteLine(username);
return Json(new { success = true } );
}
看起来数据已经正确发送了。
如果我理解正确,字符串现在应该具有来自传递数据的值。但它仍然为空。
我也尝试过使用 void 作为返回值(并且没有数据类型)。
<input type="button" value="Fatty2" onclick="ajaxMethodData()" />
我做错了什么?
【问题讨论】:
-
为什么要为参数添加 [FromBody]?这是您的 MVC 方法而不是“WebAPI”方法吗?
-
你没有在成功方法中做任何事情。
标签: javascript jquery ajax asp.net-core-mvc