Asp.Net核心验证和提交表单与Ajax?



我有一个窗体在模态弹出?

<form asp-controller="Account" asp-action="Register">
<div class="form-area" id="Register-Form" hidden>
<div class="form-group">
<input type="password" name="user_Password" class="input-field" maxlength="6" id="Register-NewPassword">
</div>
<div class="form-group">
<input type="number" class="input-field" maxlength="6" autocomplete="off" id="Register-ActiveCode"> 
</div>
<div class="form-group text-center">
<button  type="submit" onclick="return Validate_Register()" class="mybtn">Save </button>
</div>
</div>

Jquery验证:

function Validate_Register() { 
$.post("/Account/CheckActiveCode", {
Mobile: Login_Mobile, ActiveCode: Register_Active_Value
}, function (data) {
if (data == 1) {
$.alert({
title: 'Error',
content: 'Active Code is Not True',
rtl: true,
closeIcon: true,
type: 'red',
typeAnimated: true,
buttons: {
confirm: {
text: 'Ok',
btnClass: 'btn-red',
}
},
});
return false;
}       

});
return true;
}

控制器:

public JsonResult CheckActiveCode(string Mobile , string ActiveCode)
{            
if (!_user.UserIsActivate(Mobile, ActiveCode))
{
return Json(1);
}
return Json(0);
}

Controller Form for Submit:

[HttpPost]
public IActionResult Register(string mobile_User, string user_Password)
{
_user.RegisterUpdateUser(mobile_User, user_Password);

return RedirectToAction("Index", "Home");
}

我希望表单提交,如果验证(data==0)如果(data==1),表单将不会被提交,并且会显示一个错误。

尝试使用<input type="button"/>代替<button></button>,如果使用data !=1,则提交表单

html代码:

<form id="myForm" asp-controller="Account" asp-action="Register">
<div class="form-area" id="Register-Form" hidden>
<div class="form-group">
<input name="mobile_User" class="input-field" maxlength="6" id="mobile_User">
</div>
<div class="form-group">
<input type="password" name="user_Password" class="input-field" maxlength="6" id="Register-NewPassword">
</div>
<div class="form-group">
<input type="number" class="input-field" maxlength="6" autocomplete="off" id="Register-ActiveCode">
</div>
<div class="form-group text-center">
<input type="button" onclick="Validate_Register()" class="mybtn" value="Save" />
</div>
</div>
</form>

js:

function Validate_Register() {
$.post("CheckActiveCode", {
Mobile: Login_Mobile, ActiveCode: Register_Active_Value
}, function (data) {
if (data == 1) {
$.alert({
title: 'Error',
content: 'Active Code is Not True',
rtl: true,
closeIcon: true,
type: 'red',
typeAnimated: true,
buttons: {
confirm: {
text: 'Ok',
btnClass: 'btn-red',
}
},
});
} else {
$("#myForm").submit();
}
})
}

最新更新