[英]Ajax request body from view to controller is empty in ASP NET Core MVC 3
I have a scenario where I want to make an ajax call from view to controller in ASP NET Core MVC 3. The controller should then return partial view as a response.我有一个场景,我想在 ASP NET Core MVC 3 中从视图对 controller 进行 ajax 调用。然后 controller 应该返回部分视图作为响应。 The main problem is that when data gets passed to controller via ajax post request, controller finds data null.
主要问题是,当数据通过 ajax 发布请求传递到 controller 时,controller 找到数据 Z207B9Z776CC08CDAFFAE I've searched through a lot of online content on this topic, but no solution works for me.
我已经搜索了很多关于这个主题的在线内容,但没有适合我的解决方案。
Here is my controller method:这是我的 controller 方法:
[HttpPost]
public PartialViewResult AddUserForm(string firstName, string lastName)
{
// some stuff happens then
return PartialView();
}
My Ajax post method in view:我的 Ajax 后视图中的方法:
<script>
function replaceContentsOfDiv() {
var f = $('#fName').val();
var l = $('#lName').val();
$.ajax({
url: '@Url.Action("AddUserForm", "Reservation")',
contentType: 'application/json',
data: JSON.stringify({ firstName: this.f, lastName: this.l }),
type: "POST",
success: function(data) {
$('#placeHolderDiv').html(data);
},
error: function() {
alert("something is wrong");
}
});
}
</script>
The data from this js script ( var f
and var l
have valid values. However, if I want to log out string firstName
and string lastName
in controller method, they are both null. This can be tested with I. e. logger.LogInformation((firstName == null).ToString())
.此 js 脚本中的数据(
var f
和var l
具有有效值。但是,如果我想在 controller 方法中注销string firstName
和string lastName
,它们都是 null。这可以用logger.LogInformation((firstName == null).ToString())
。
Anyone knows what I'm doing wrong so that the data that gets passed into controller is null?任何人都知道我做错了什么,因此传递到 controller 的数据是 null? I even tried adding
[FromBody]
annotations to AddUserForm
parameters, but no success either.我什至尝试将
[FromBody]
注释添加到AddUserForm
参数,但也没有成功。
EDIT: fixed some typo in my JS script.编辑:修复了我的 JS 脚本中的一些错字。
You just need to change your ajax like following:你只需要改变你的 ajax 如下:
$.ajax({
url: '@Url.Action("AddUserForm", "Reservation")',
data: {
firstname: f,
lastname: l
},
type: "POST",
success: function(data) {
$('#placeHolderDiv').html(data);
},
error: function() {
alert("something is wrong");
}
});
I then found the solution.然后我找到了解决方案。 The problem was how the request was called.
问题是如何调用请求。 I then just used regular jQuery post method like this:
然后我只使用了常规的 jQuery 发布方法,如下所示:
<script>
function replaceContentsOfDiv() {
let data = {
firstName: document.getElementById("fName").value,
lastName: document.getElementById("lName").value
}
console.log(data);
$.post('@Url.Action("AddUserForm", "Reservation")', data, function (data) {
$('#placeHolderDiv').html(data);
});
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.