我想在.Net Core 3 MVC中提交表单而不刷新页面,但它仍然刷新。
HTML:
<div class="form-popup" id="myForm">
<div id="CRDone" style="display:none;">
<i class="fa fa-check" style="color:green;" aria-hidden="true"></i>
<br/>
<p style="color:green;">We've recieved your request</p>
</div>
<form id="CRForm" method="post" asp-action="SaveContactRequest" class="form-container">
<h1>Get in touch</h1>
<label for="CRName"><b>Name</b></label>
<input id="CRName" type="text" placeholder="What's your name" name="Name" required>
<label for="CRCompany"><b>Company</b></label>
<input id="CRCompany" type="text" placeholder="Where do you work" name="Company" required>
<label for="CRDepartment"><b>Department</b></label>
<input id="CRDepartment" type="text" placeholder="Enter your Department" name="Department" required>
<label for="CRPosition"><b>Position</b></label>
<input id="CRPosition" type="text" placeholder="Enter your Position" name="Position" required>
<label for="CRPhone"><b>Phone Number</b></label>
<input id="CRPhone" type="text" placeholder="Write your Mobile Number" name="Phone" required>
<label for="CREmail"><b>Email</b></label>
<input id="CREmail" type="text" placeholder="Write your Email" name="Email" required>
<label for="CRMessage"><b>Message</b></label>
<input id="CRMessage" type="text" placeholder="Write your Message" name="Message">
<button type="submit" class="btn">Request</button>
</form>
</div>
Javascript
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: frmValues,
processData: false,
contentType: false
}).done(function (result) {
console.log(result);
if (result == true) {
$("CRDone").show();
$("CRForm").hide();
}
else {
alert('an Error has occurred, please try again!');
}
}).fail(function (result) {
alert('an Error has occurred, please try again');
});
});
Controller
[HttpPost]
public async Task<bool> SaveContactRequest(ContactRequest request)
{
return await request.SaveRequest();
}
我还尝试为按钮创建 onclick 函数而不是表单提交,并尝试从按钮事件调用该函数,所有这些都倾向于更改页面并在空白页面中显示正确或错误的单词。
最佳答案
您需要防止提交“非ajax”表单
这可以像
一样简单<form id="CRForm" method="post" onsubmit="return false;"
或者你可以使用 jquery 尝试:
$(document).on('submit', '#CRForm', function(e){
e.preventDefault();
return false;
});
不使用按钮 type="submit"也可能有帮助
也许只使用一个跨度
<span class="btn">Request</span>
根据您的代码更新:
$("#CRForm").on("submit", function (event) {
event.preventDefault();
var $this = $(this);
...
关于javascript - 使用Ajax在.Net Core 3中提交表单而无需刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59576126/