我使用以下按钮正常工作并按预期调用操作
保存按钮
@using (Html.BeginForm("edit", "user", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="actionbtn" value="Save" name="buttonType" />
</div>
</div>
}
检查按钮
@using (Html.BeginForm("Check", "User"))
{
<input type="submit" id="btnConnect" value="Check" />
<span id='result'></span>
}
现在当我添加以下代码时,如果操作成功与否应添加一些文本,保存按钮不会调用操作,我在这里做错了什么?
$("form").submit(function (e) {
// Cancel the default submission
e.preventDefault();
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
});
我试图删除e.preventDefault();没有成功...
答案 0 :(得分:1)
首先,您需要在表单中添加ID:
@using (Html.BeginForm("Check", "User",FormMethod.Post, new { Id = "CheckForm" })
然后,您只需要为所需的表单添加提交事件处理程序:
$("#CheckForm").submit(function (e) {
// Cancel the default submission
e.preventDefault();
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("Successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
});
还有另外一件事。当您像这样提交Ajax时 - 那么它将提交空表单。你需要什么?
答案 1 :(得分:1)
您需要像这样检查通过哪个按钮提交的表单。
你必须这样做才能限制它:
$("form").submit(function (e) {
// Cancel the default submission
e.preventDefault();
if($(this).find('input[type="submit"]').val() === "Check") // form submitted via Check button
{
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
}
else
{
// form submitted from Save button
}
});