【问题标题】:passing Json Post to the controller returns undefined asp.net core将 Json Post 传递给控制器​​返回未定义的 asp.net 核心
【发布时间】: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


    【解决方案1】:

    您在此处将请求作为对象发送

        $.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);
        }
    

    【讨论】:

    • 一个string 是一个object :)
    • 基本上没有,它是一个结构体。除非您使用带有大写字母 S 的字符串,否则它是一个对象。
    • 错误(string 是引用类型,是 String 的别名)。并且 OP 正在发送无法绑定到 MyTodoText 模型的 { getText: 'someTextValue' }
    • 你怎么知道mondelbinder不能绑定呢?你见过还不存在的对象 MyTodoText 吗?它会起作用的,别担心。
    • 因为ModelBinder(或任何c#代码)不能做MyTodoText getText = "someTextValue";(但我看到你刚刚编辑它以更改参数的名称)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2021-09-27
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多