2016-11-18 38 views
0

我有一個MVC Ajax回調函數,用於檢查用戶輸入是否有效。此回調通過相關模型屬性上的[Remote]屬性進行調用。通過Ajax遠程驗證返回警告(不是錯誤)

我改變了我的設計,並且我已經決定,如果值不正確,我真的很想警告用戶,但我不想讓不正確的值阻止模型驗證。

一個快速搜索出現了幾個線程,描述了非常複雜的解決方案,用於接入類似於MVC(例如this SO post)中的「不顯眼驗證」魔法的「不顯眼警告」。我不是在尋找一個通用的解決方案,我不想花費大量的時間和精力,但是我想知道是否有一些Ajax專家知道我可以從Ajax服務器例程返回的東西,導致不引人注意的驗證客戶端代碼放置消息而不觸發驗證錯誤的效果。

僅供參考,我現有的服務器端的代碼如下所示:

public async Task<ActionResult> CouponCodeExists(string couponCode, int? planId) 
    { 
     if (some_logic) { 
      return Json("Coupon code is already taken", JsonRequestBehavior.AllowGet); 
     } else { 
      return Json(true, JsonRequestBehavior.AllowGet); 
     } 
    } 
+1

只是讓你自己在輸入'.change()Ajax調用'事件,在成功回調中,顯示消息(如果您不希望它觸發驗證錯誤,請移除「RemoteAttribute」) –

+0

@StephenMuecke如果缺少任何更好的答案,我想接受您的評論作爲首選答案。如果你願意將它作爲「答案」發佈,我會接受它並且完成這個問題。 –

回答

1

一個RemoteAttribute是一個驗證屬性,並觸發其將增加驗證錯誤jQuery.validate.js,防止從形式提交。如果您只需要一條警告消息,並且仍然允許表單提交,則可以在輸入.change()事件中創建自己的ajax調用。

假設您在該視圖中有@Html.TextBoxFor(m => m.couponCode),請爲該消息添加一個佔位符 - 例如<div id="couponwarning">Coupon code is already taken</div>,樣式爲display: none;。然後添加下面的腳本

var url = '@Url.Action("CouponCodeExists")'; 
var warning = $('#couponwarning'); 
$('#couponCode').change(function() { 
    var code = $(this).val(); 
    var id = .... // the value of your planId input? 
    $.get(url, { couponCode: code, planId: id }, function(response) { 
     if (response) { 
      warning.show(); 
     } 
    }); 
}); 
$('#couponCode').keyup(function() { 
    warning.hide(); 
}); 

和方法可以只返回true顯示消息,或null

if (some_logic) { 
    return Json(true, JsonRequestBehavior.AllowGet); 
} else { 
    return Json(null, JsonRequestBehavior.AllowGet); 
}