jQuery Ajax で ASP.NET MVC 検証を使用するには? 質問する

jQuery Ajax で ASP.NET MVC 検証を使用するには? 質問する

次のような単純な ASP.NET MVC アクションがあります。

public ActionResult Edit(EditPostViewModel data)
{

}

次のような検証属性がありますEditPostViewModel:

[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }

ビューでは次のヘルパーを使用しています:

 @Html.LabelFor(Model => Model.EditPostViewModel.Title, true)

 @Html.TextBoxFor(Model => Model.EditPostViewModel.Title, 
                        new { @class = "tb1", @Style = "width:400px;" })

このテキスト ボックスが配置されているフォームで送信を実行すると、最初にクライアントで検証が実行され、次にサービス ( ModelState.IsValid) で検証が実行されます。

さて、いくつか質問があります。

  1. これを代わりに jQuery ajax 送信で使用することはできますか? 私が行っているのは、単にフォームを削除し、送信ボタンをクリックすると JavaScript がデータを収集して実行するというものです$.ajax

  2. サーバー側はModelState.IsValid動作しますか?

  3. 検証の問題をクライアントに転送し、ビルド int validation( @Html.ValidationSummary(true)) を使用しているかのように提示するにはどうすればよいですか?

Ajax呼び出しの例:

function SendPost(actionPath) {
    $.ajax({
        url: actionPath,
        type: 'POST',
        dataType: 'json',
        data:
        {
            Text: $('#EditPostViewModel_Text').val(),
            Title: $('#EditPostViewModel_Title').val() 
        },
        success: function (data) {
            alert('success');
        },
        error: function () {
            alert('error');
        }
    });
}

編集1:

ページに含まれるもの:

<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

ベストアンサー1

クライアント側

ライブラリの使用はjQuery.validateセットアップが非常に簡単です。

ファイルに次の設定を指定しますWeb.config

<appSettings>
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
</appSettings>

ビューを構築するときは、次のようなことを定義します。

@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title, 
                                new { @class = "tb1", @Style = "width:400px;" })
@Html.ValidationMessageFor(Model => Model.EditPostViewModel.Title)

注記:これらはフォーム要素内で定義する必要がある

次に、次のライブラリを含める必要があります。

<script src='@Url.Content("~/Scripts/jquery.validate.js")' type='text/javascript'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")' type='text/javascript'></script>

これにより、クライアント側の検証が可能になります。

リソース

サーバ側

注記:jQuery.validationこれはライブラリ上の追加のサーバー側検証のみを目的としています

おそらく次のようなものが役に立つでしょう:

[ValidateAjax]
public JsonResult Edit(EditPostViewModel data)
{
    //Save data
    return Json(new { Success = true } );
}

ValidateAjax属性は次のように定義されます。

public class ValidateAjaxAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
            return;

        var modelState = filterContext.Controller.ViewData.ModelState;
        if (!modelState.IsValid)
        {
            var errorModel = 
                    from x in modelState.Keys
                    where modelState[x].Errors.Count > 0
                    select new
                           {
                               key = x,
                               errors = modelState[x].Errors.
                                                      Select(y => y.ErrorMessage).
                                                      ToArray()
                           };
            filterContext.Result = new JsonResult()
                                       {
                                           Data = errorModel
                                       };
            filterContext.HttpContext.Response.StatusCode = 
                                                  (int) HttpStatusCode.BadRequest;
        }
    }
}

これは、すべてのモデル エラーを指定する JSON オブジェクトを返します。

回答例は次のようになります

[{
    "key":"Name",
    "errors":["The Name field is required."]
},
{
    "key":"Description",
    "errors":["The Description field is required."]
}]

$.ajaxこれは、呼び出しのエラー処理コールバックに返されます。

返されたデータをループして、返されたキーに基づいて必要に応じてエラーメッセージを設定できます($('input[name="' + err.key + '"]')入力要素を見つけるには次のようなものだと思います)。

おすすめ記事