提问者:小点点

为什么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”,那么脚本就不能工作(除非字段中没有任何输入)。

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

我希望这是有意义的,如果我没有提供足够的信息,我很抱歉

谢谢


共1个答案

匿名用户

假设#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');
      }
    });
  });
});