首页 > 解决方案 > 为什么在 JQuery 脚本中返回 False 会阻止信息进入 SQL 数据库

问题描述

编程新手 - 目前正在为我的学徒项目做一个项目。我在 Visual Studio 中设置了一个 asp.net 应用程序。我添加了一个控制器并创建了一个“联系人”页面。这工作正常,用户输入发送到数据库到目前为止没有问题。我的下一步是改进 UI,所以我编写了以下 Jquery 代码:

$(document).ready(function () {
    $("#show").hide();
    $("#click").click(function () {
        $("#hide").hide();
        $("#show").toggle();
        return false;
    });
});

这会隐藏包含输入字段和提交按钮(用于联系页面)的 div,并显示带有“谢谢”消息的 div。这个函数确实隐藏了 div,但这会阻止用户输入被发送到数据库。

这是来自控制器的 C# 代码:

    public async Task<IActionResult> Create([Bind("Id,FullName,EmailAddress,Message")] Contact contact)
    {
        if (ModelState.IsValid)
        {
            _context.Add(contact);
            await _context.SaveChangesAsync();            
        }
        return View(contact);
    }

JQuery 脚本中的“return false”似乎是问题所在,但如果我“return true”,则脚本不起作用(除非字段中没有任何输入)。

我的问题是如何让脚本和后端同时工作?

如果我没有提供足够的信息,希望这是有道理的并道歉

谢谢

标签: jquery

解决方案


假设这#click是一个提交按钮,则从其处理函数返回 false 将阻止父表单提交到服务器。如果您想让用户保持在同一页面上,而不是在表单提交发生时重定向,您将需要停止表单提交并使用 AJAX 将数据发送到您的控制器。

值得庆幸的是,在 jQuery 中,使用该$.ajax()方法很容易做到这一点。但是,在此过程中需要进行一些小调整。试试这个,注意评论:

$(document).ready(function() {
  $("#show").hide(); // I'd suggest doing this in CSS, not JS
  
  // hook to the submit of the form, not the click of the button. 
  // This is for web accessibility reasons, ie. users who browse using the keyboard only
  $('#yourForm').on('submit', function(e) { 
    // use preventDefault instead of return false. The latter prevents event bubbling 
    // which can cause unintended consequences.
    e.preventDefault(); 
    
    // send the data to the server via AJAX
    $.ajax({
      url: this.action, // set the URL to action of the form
      method: this.method, // set the HTTP verb to match the form, generally a POST in this case
      data: $(this).serialize(), // serialise the form data in to a querystring to send in the request body
      success: function() {
        // if the request worked, update the UI
        $("#hide").hide();
        $("#show").toggle();
      },
      error: function() {
        console.log('something went wrong, debug the request in devtools');
      }
    });
  });
});

推荐阅读