将Json Post传递给控制器​​将返回未定义的asp.net核心

时间:2018-07-27 13:21:35

标签: json ajax asp.net-mvc asp.net-core asp.net-ajax

我正在尝试使用Ajax动态保存文本,但是传递给控制器​​的值始终为null。

这是我的代码。

Index.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为null。当我从Jason登录newText变量时,向我显示了正确的值,但仍将null传递给控制器​​。

1 个答案:

答案 0 :(得分:0)

您将请求作为对象发送到这里

    $.ajax({
        type: "POST",
        url: "Home/AddText",
        data: JSON.stringify({getText: newText}), // <-- makes an object
        contentType: "application/json",
        success: function (result) {
            $("#myTable").append("<tr><td>" +
                result.Text + "</td></tr>");
            console.log(result.Text);
        }
    })

创建一个适当的对象并将其传递给您的控制器。

  [HttpPost]
    public JsonResult AddText([FromBody]MyTodoText text)
    {
        var newText = new TodoModel();

        newText.Text = text.getText;
        return Json(newText);
    }