如何解决在C#ASP.NET Core MVC中使用AJAX将数据从视图传递到控制器
我尝试查看类似问题的答案,但是这些问题都不适合我的代码。我尝试了很多不同的事情,它所要做的就是发布全名,然后将其显示在视图中。 查看代码:
<script type="text/javascript">
$(document).ready(function () {<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo2').click(function () {
var fullName = $('#fullName').val();
var payload = {fn : fullName};
$.ajax({
type: 'POST',url: '/demo/demo2/',contentType: 'application/json',data: JSON.stringify(payLoad),success: function (result) {
$('#result2').html(result);
}
});
});
</script>
<fieldset>
<legend>Demo 2</legend>
Full Name <input type="text" id="fullName" />
<input type="button" value="Demo 2" id="buttonDemo2" />
<br />
<span id="result2"></span>
</fieldset>
控制器代码:
[HttpPost]
public IActionResult Demo2(string fullName)
{
return new JsonResult("Hello " + fullName);
}
解决方法
首先,当您通过ajax将字符串传递给action时,应确保接收的参数名称与传入的参数名称相同。
因此,您应该将var payload = {fullName: fullName};
更改为public IActionResult Demo2(string fullName)
,或将public IActionResult Demo2(string fn)
更改为JSON.stringify
。
然后,因为只传递了一个字符串而不是对象参数,所以您不需要使用contentType: 'application/json'
并删除 <script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo2').click(function () {
var fullName = $('#fullName').val();
var payload = { fullName: fullName }; // change name
$.ajax({
type: 'POST',url: '/demo/demo2/',// contentType: 'application/json',// remove this line
data: payload,//remove JSON.stringify
success: function (result) {
$('#result2').html(result);
}
});
});
});
</script>
<fieldset>
<legend>Demo 2</legend>
Full Name <input type="text" id="fullName" />
<input type="button" value="Demo 2" id="buttonDemo2" />
<br />
<span id="result2"></span>
</fieldset>
。
这是详细的代码:
[HttpPost]
public IActionResult Demo2(string fullName)
{
return new JsonResult("Hello " + fullName);
}
控制器:
Map<Integer,List<Integer>> map = new HashMap<>();
if (!map.containsKey(1)) {
map.put(1,new ArrayList<>());
}
map.get(1).add(2);
这是测试结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。