JQuery跳过整个AJAX部分

时间:2017-11-20 19:38:09

标签: c# jquery ajax asp.net-core-mvc

我无法弄清楚为什么,当单步执行时,它只是跳过调用控制器中方法的Ajax部分。

[HttpPost]
    public JsonResult findUser(userIdModel lookfor)
    {
        Citrix citrix = new Citrix();
        List<string[]> result = citrix.findUser(lookfor.username);
        FindUserModel model = new FindUserModel();
        result.ForEach(x => model.ServerName = x[1]);
        return Json(model);
    }

@Html.TextBox("strUser", "", new { id = "userid" })
<input type="submit" value="Find" class="btn btn-default" id="lookup" />
<text id="results"></text>
<script>
    $('#lookup').click(function (event) {
        strUser = $('#userid').val();
        lookfor = JSON.parse('{ "username":"' + strUser + '" }');
        $.ajax({
            type: "POST",
            url: "/Home/findUser",
            data: lookfor,
        }).done(function (data) {
            $('#results').val(data.servername)
        });
    });
</script>

2 个答案:

答案 0 :(得分:1)

更好的方法是绑定表单提交事件处理程序而不是提交按钮的onclick,@ rory是正确的,你没有返回false

<script>
    $("form").submit(function (event) {
        strUser = $('#userid').val();
        lookfor = JSON.parse('{ "strUser":"' + strUser + '" }');
        $.ajax({
            type: "POST",
            url: "/Home/findUser",
            data: lookfor,
        }).done(function (data) {
            $('#results').val(data.servername)
        });
        return false;
    });
</script>

如果您的网页上有多个表单,则应将$('form')替换为formId

答案 1 :(得分:1)

而不是使用提交

<input type="submit" value="Find" class="btn btn-default" id="lookup" />

使用按钮

<input type="button" value="Find" class="btn btn-default" id="lookup" />

还有一件事,让我们确保您没有收到错误。将此添加到您的ajax调用

  $("form").submit(function (event) {
        strUser = $('#userid').val();
        lookfor = JSON.parse('{ "strUser":"' + strUser + '" }');
        $.ajax({
            type: "POST",
            url: "/Home/findUser",
            data: lookfor,
        }).done(function (data) {
            $('#results').val(data.servername)
        })
.fail(function (xhr, ajaxOptions, thrownError) {
        // alert(thrownError + "--" + xhr.responseText);
        var data = xhr.responseText;
        var jsonResponse = JSON.parse(data);
         alert(jsonResponse['Message']);
 });