【问题标题】:How to pass string to Controller using AJAX如何使用 AJAX 将字符串传递给控制器
【发布时间】:2018-06-12 05:25:43
【问题描述】:

当按下按钮时,我似乎无法完成将字符串传递给控制器​​的这个非常简单的任务。接收到的数据,始终为空。谁能告诉我我做错了什么?

表格:

<form>
    <div class="form-group">
        <label for="ProcessName" class="control-control">Process Name</label>
        <input id="ProcessName" class="form-control" placeholder="Choose process name">
        <small id="subtitle" class="form-text text-muted">Text under input field.</small>
    </div>
    <button type="submit" class="btn btn-primary" id="addElement">Submit</button>
</form>

Javascript:

$(function () {
    $("#addElement").click(function () {
        var processName = $("#ProcessName").val();

        // I've tried this method
        $.post('@Url.Action("AddProcessName")', processName, function (data, status) {
                    alert(data)
        });

       // And also this one, but both of them don't work.
       // I did not try them at the same time, of course
        $.ajax({
            type: "POST",
            url: '@Url.Action("AddProcessName")',
            data: processName,
            dataType: 'text',
            success: function (response) {
                alert(response)
                };
        });
    });
});

服务器端:

[HttpPost]
public IActionResult AddProcessName(string data)
{
    pm.ID = 1;
    pm.Name = data; // I put a breakpoint here to check the value of 'data'
    return Content(pm.Name);
}

【问题讨论】:

    标签: jquery asp.net ajax asp.net-mvc razor


    【解决方案1】:

    您告诉您的 Action 需要一个名为 data 的变量,但您并没有发送它。您需要将 jQuery AJAX 请求的 data 属性更改为:

    data: { data: processName },
    

    我还建议您从 Action 返回 JSON,因为纯文本充其量可能是片状的,因为可能会或可能不会解释空格。试试这个:

    $("#addElement").click(function () {
      $.ajax({
        type: "POST",
        url: '@Url.Action("AddProcessName")',
        data: { 
          data: $("#ProcessName").val() 
        },
        dataType: 'json',
        success: function(response) {
          // use console.log for debugging, and access the property of the deserialised object
          console.log(response.Name); 
        };
      });
    });
    
    [HttpPost]
    public IActionResult AddProcessName(string data)
    {
        pm.ID = 1;
        pm.Name = data;
        return Json(new { Name = pm.Name });
        // or just:
        // return Json(pm);
    }
    

    【讨论】:

    • 有效!非常感谢。感谢您提示改用 JSON。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2016-07-18
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 2017-10-23
    • 2021-08-02
    相关资源
    最近更新 更多