我正在编写允许您优化SQL查询的Web应用程序。

我有这样的看法:

<div id="codeeditor" style="margin-right:20px; float:left"  >
    <script>
        var editor = CodeMirror(document.getElementById("codeeditor"), {
        mode: "sql",
        theme: "dracula",
        tabSize: 5,
        lineNumbers: true,
        });
        editor.setSize(500, 500);
    </script>
    <input type="submit" value="start" id="btnClick" />
</div>

<div id="codeeditor1">
    <script>
        var editor1 = CodeMirror(document.getElementById("codeeditor1"), {
            mode: "sql",
            theme: "dracula",
            tabSize: 5,
            lineNumbers: true,

        });
        editor1.setSize("45%", 500);
   </script>

</div>


@section scripts{
<script type="text/javascript">
    $(document).ready(function () {
       $("#btnClick").click(function () {
            var f = {};
            f.url = '@Url.Action("Demo", "Home")';
            f.type = "POST";
            f.dataType = "json";
            f.data = JSON.stringify({ sourceSqlCode: editor.getValue() });
            f.contentType = "application/json";
            editor1.setValue(@ViewBag.readyQuery);
            f.success = function (response) {
                alert("success");
            };
            f.error = function (response) {
                alert("err");
            };
            $.ajax(f);
        });
    });
</script>
}


这是我的控制器,它处理按钮单击

[HttpPost]
    public ActionResult Demo(string sourceSqlCodee)
    {
        //here I use my libraries and optimize query

        ViewBag.readyQuery= optimizedQuery;

        return View();
    }


我需要做的就是通过单击按钮将查询传递给控制器​​,然后在修改为codeeditor1后将其传递回视图。

它根本不起作用,因为脚本的运行时间早于我的控制器方法。我怎样才能做到这一点?谢谢!

最佳答案

我认为您应该只在控制器操作中返回一个字符串,例如:

[HttpPost]
public string Demo(string sourceSqlCode)
{
    //here I use my libraries and optimize query

    return optimizedQuery;
}


然后,在您的AJAX成功方法中,执行以下操作:

f.success = function (response) {
    editor1.setValue(response);
};

10-08 18:38