Asp.net-Mvc-3

如何在 MVC 3 中掛鉤 jQuery 驗證不顯眼的錯誤?

  • December 1, 2020

尋找一種方法來掛鉤錶單的客戶端失敗條件。

如果驗證失敗,我需要重新啟用送出按鈕,以便他們重試。

我發現以下內容:在 ASP.NET MVC 3 中使用不顯眼的驗證,當表單無效時如何採取措施?這可能有效,但我希望從一個中心位置執行此操作,因為可以從多個地方送出表單。

更新:

假設您有一個帶有“.goButton”類的輸入標籤,這個函式似乎工作得很好。

<script language="javascript" type="text/javascript">
   $(".goButton").click(function () {
       if (!$(this).closest("form").valid()) {
           return false;
       }
       $(".goButton").after("Please wait...");
       $(".goButton").hide();
   });
</script>

然後,您可以從一個中心位置掛鉤所有表格 - 請注意所有表格都將被掛鉤。而不是$("#formId")在範例中使用,只需使用$("form").submit()並且該委託將被呼叫任何表單的送出,在該方法中,您可以呼叫驗證檢查並返回 true(送出表單)或 false 以防止它。

像這樣的東西從我的頭頂

$("form").submit(function () {
 if (!$(this).valid()) {
     return false;
 }
 else
 {
     return true;
 }
});

我必須解決 OPs 問題,它更簡單、更可定制:

在 C# MVC 控制器中:

[HttpPost]
public ActionResult CreateDirectory(string DirectoryName)
{
   return Content("Success");
}

在頁面 JQuery 中:

<script>
var jqxhr = $.post("/<Directory>/<File>", { myString: longString }, function () {
   if(jqxhr.responseText == 'Success')
       alert('Yay its working!');
   else
       alert('Failure its not working!');
})
.done(function () {
   //alert("second success");
})
.always(function () {
   //alert("finished");
})
.fail(function () {
   alert("Connection Error! Either the Server is offline or there is no internet connection.");
});
<script>

當然,這是完全可定制的,而且很享受!通過編輯控制器和 JQuery 程式碼以適合您的建議。

這就像處理 JQuery 方面:

if(jqxhr.responseText == 'Success') alert('Yay its working!');

引用自:https://stackoverflow.com/questions/6494008