MVC ソリューション テンプレートに付属する jQuery 検証を使用していると仮定すると、javascript ハンドラーでバリデーターにエラーを追加する必要があります。showErrors
validator にはメソッドがあります。
クライアント側:
var formSubmitCallback = function(result){
var validator = $(this).data('validator');
if(!result.IsValid && validator)
validator.showErrors(result.Errors); // uses jquery validator to highlight the fields
// process the rest of the result here
// if result.Action == ActionTypes.Redirect
// location.href = result.Url
// etc
}
ここで、サーバーからの結果オブジェクトを標準化して、 でフォーマットされた json オブジェクトを返す必要がありました{ "FieleName": "Error Message" }
。それを達成するために、サーバー側にいくつかController
の拡張機能を作成しました。ViewModel
サーバー側:
public ActionResult SomeAction(Model someModel){
if(ModelState.IsValid)
// save
else
// other stuff
// always return this.AjaxSubmit.
// Extension function will add Errors, and IsValid to the response data
return this.AjaxSubmit(new ClientAction{
Action = ClientActionType.Redirect,
Url = "/Some/Redirect/Route"
});
}
注:これを振り返ってみると、それを機能させるために少しカスタムコードを書きました。最終的にクライアントとサーバーのコードを github のサンプルと共に追加します。しかし、これは一般的な考え方です。
必要なサーバー クラスと拡張機能は次のとおりです。
// GetAllErrors is a ModelState extension to format Model errors for Json response
public static Dictionary<string, string> GetAllErrors(this ModelStateDictionary modelState)
{
var query = (from state in modelState
where state.Value.Errors.Count > 0
group state by state.Key into g
select new
{
FieldName = g.Key,
FieldErrors = g.Select(prop => prop.Value.Errors).First().Select(prop => prop.ErrorMessage).ToList()
});
return query.ToDictionary(k => k.FieldName, v => string.Join("<br/>", v.FieldErrors));
}
// Controller result extension to return from actions
public static JsonResult AjaxSubmit(this Controller controller, ClientAction action)
{
if (controller == null) return new JsonResult { Data = action };
var result = new AjaxSubmitResult
{
Errors = controller.ModelState.GetAllErrors(),
IsValid = controller.ModelState.IsValid,
ClientAction = action
};
return new JsonResult{ Data = result };
}
// Action to perform on the client after a successful, valid response
public class ClientAction
{
public ClientActionType Action { get; set; }
public string Url { get; set; }
public string Function { get; set; }
public object Data { get; set; }
public Dictionary<string, string> Updatables { get; set; }
}
public enum ClientActionType
{
Redirect,
Ajax,
Function,
Modal,
Message,
FunctionAndMessage
}