为什么JQuery脚本中的Return 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",则脚本将不起作用(除非字段中没有任何输入(。

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

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

感谢

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

最新更新