【发布时间】:2019-01-04 15:11:46
【问题描述】:
我正在尝试使用 Ajax 动态保存文本,但传递给控制器的值始终为空。
这是我的代码。
索引.cshtml
@model MvcAndAjax.Models.TodoModel
@{
ViewData["Title"] = "Home Page";
}
<h2>Things that I need to do!</h2>
<div>
<span>Text:</span>@Html.TextBoxFor(x => x.Text, new {@class ="form-control"})<br/>
<p><a class="btn" onclick="SaveUser()">Save</a></p><br />
</div>
<div class="row">
<h2>Task's list</h2>
<table id="myTable">
<tr>
<th>ID</th>
<th>Text</th>
</tr>
</table>
</div>
<style>
#myTable tr th{
color: white;
width: 300px;
height: 40px;
text-decoration: solid;
background-color: yellowgreen;
padding: 10px;
}
</style>
<script>
function SaveUser() {
var newText = $("#Text").val();
$.ajax({
type: "POST",
url: "Home/AddText",
data: JSON.stringify({getText: newText}),
contentType: "application/json",
success: function (result) {
$("#myTable").append("<tr><td>" +
result.Text + "</td></tr>");
console.log(result.Text);
}
})
}
</script>
和控制器
[HttpPost]
public JsonResult AddText([FromBody]string getText)
{
var newText = new TodoModel();
newText.Text = getText;
return Json(newText);
}
但我总是不确定。当我调试时,它显示 getText 为空。当我从 Jason 记录 newText 变量时,它显示了正确的值,但仍将 null 传递给控制器。
【问题讨论】:
标签: json ajax asp.net-mvc asp.net-core asp.net-ajax