2017-10-21 3 views
0

ゴール:
入力に基づいてエラーを取得する場合は、Webページをリフレッシュせずにajaxに関連してValidationSummaryに表示する必要があります。Validationsummary in Ajaxでエラーメッセージを表示

問題:
私はそれをしようとしましたが、うまくいきません。

どの部分が欠けていますか?

ありがとうございました!

情報:
*私はいくつかのウェブページを見つけましたが、私の目的に正確には合致しません。私はASP.netのMVCを使用しています*

@model WebApplication1.Controllers.PersonnelModel 

@{ 
    ViewBag.Title = "Ajax"; 
} 

<h2>Ajax</h2> 



<h2>AjaxViewModel</h2> 
@using (Html.BeginForm("HtmlViewModel", "Home", null)) 
{ 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>PersonnelModel</legend> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.UserName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.UserName) 
      @Html.ValidationMessageFor(model => model.UserName) 
     </div> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.MailAdress) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.MailAdress) 
      @Html.ValidationMessageFor(model => model.MailAdress) 
     </div> 
    </fieldset> 
    <p> 
     <input type="submit" value="Html Form Action" /> 
    </p> 
} 

<br/> 
<br /> 




<h2>AjaxViewModel</h2> 
@using (Ajax.BeginForm("AjaxViewModel", "Home", new AjaxOptions { UpdateTargetId = "result" })) 
{ 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>PersonnelModel</legend> 

     <div id="result"></div> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.UserName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.UserName) 
      @Html.ValidationMessageFor(model => model.UserName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.MailAdress) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.MailAdress) 
      @Html.ValidationMessageFor(model => model.MailAdress) 
     </div> 
    </fieldset> 
    <p> 
     <input type="submit" value="Ajax Form Action" /> 
    </p> 
} 



<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script src="https://cdn.jsdelivr.net/npm/[email protected]/jquery.unobtrusive-ajax.min.js"></script> 

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Security; 

namespace WebApplication1.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      return View(); 
     } 


     [HttpPost] 
     public ActionResult HtmlViewModel(PersonnelModel Pmodel) 
     { 
      return Content("Hi " + Pmodel.UserName + ", Thanks for the details, a mail will be sent to " + Pmodel.MailAdress + " with all the login details.", "text/html"); 
     } 


     [HttpPost] 
     public ActionResult AjaxViewModel(PersonnelModel Pmodel) 
     { 
      /* 
      ModelState.AddModelError("", "login is fail"); 
      return View("Index", Pmodel); 
      */ 

      return Content("Hi " + Pmodel.UserName + ", Thanks for the details, a mail will be sent to " + Pmodel.MailAdress + " with all the login details.", "text/html"); 
     } 

    } 



    public class PersonnelModel 
    { 
     [Required(ErrorMessage = "UserName Required.")] 
     public string UserName { get; set; } 

     [Required(ErrorMessage = "Email id Required.")] 
     public string MailAdress { get; set; } 
    } 

} 
+0

私は簡単な方法でこれを行うための答えを更新しました。ご覧ください – Shyju

答えて

2

EDIT - 2017年3月11日:この

が部分図を作成する簡単な方法がありますフォームの場合は、Form.cshtmlとし、フォームに必要なマークアップを移動してみましょう。あなたのajax形式の場合は、data-ajax-modeの属性値をreplaceに、data-ajax-updateの値を同じフォームのIDに設定します。

あなたはAjax.BeginFormヘルパーメソッドを使用している場合、これはあなたがたときにあなたのメインビュー、アクションメソッドでは、単純な呼び出し、この部分図

@model PersonnelModel 
<h2>My form below</h2> 
@Html.Partial("Form",Model) 

さて、今すぐ

@model PersonnelModel 
@using (Ajax.BeginForm("Create", "Home", 
    new AjaxOptions { UpdateTargetId = "myform", 
           InsertionMode = InsertionMode.Replace },new { id="myform"})) 
{ 
    @Html.ValidationSummary("", true) 

    @Html.TextBoxFor(f => f.UserName) 
    @Html.ValidationMessageFor(model => model.UserName) 

    @Html.TextBoxFor(f => f.MailAdress) 
    @Html.ValidationMessageFor(model => model.MailAdress) 

    <input type="Submit" id="submit" value="Submit" class="btn btn-default" />  
} 

を行います方法ですモデル状態の検証に失敗した場合は、部分ビューを返します。

public ActionResult Create(PersonnelModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // to do : Save 
    } 
    if (Request.IsAjaxRequest()) 
    { 
     return PartialView("Form",model); 
    } 
    return View(model); 
} 

今、あなたは、フォームやモデルの状態の検証が失敗した送信したときに、アクションメソッドのコードは、(検証ヘルパーによって生成された)検証エラーメッセージとjquery.unobtrusive-ajax.jsライブラリコードと部分図の結果を返します置き換えられます(理由jQueryセレクタ#data-ajax-update(フォームタグとその内容)の結果の内容をサーバーから返されたレスポンスとともに返すように指定しています(data-ajax-mode="replace")。

これはそれを行う必要があります。かみそりビューが実行されますときHtml.ValidationSummaryメソッドが実行されます(下記)私の古いアプローチ


に比べて少なく、クライアント側のコード、。通常のフォーム投稿(非Ajax)を行っている場合、アクションのメソッドは通常、モデルの検証が失敗したとき(同じようなコードを書いたと仮定して)、剃刀のビューコードが実行され、ValidationSummaryメソッドが検証エラーモデル状態辞書から取り出し、エラーメッセージを表示する。あなたはヘルパーがいくつかの余分なデータがフォームに属性を生成し、限り、あなたはjquery.unobtrusive-ajax.min.jsスクリプトファイルが含まれているようになるAjax.BeginFormヘルパーメソッドを使用する場合

、フォーム提出がハイジャックされ、それはAjaxのフォームが代わりに提出行います。

モデル検証メッセージをレンダリングする場合は、モデル検証エラーを明示的に読み取って、クライアントサイドコードがUIで読み取って表示できるJSON応答として返す必要があります。

あなたのビューで今すぐ
[HttpPost] 
public ActionResult Index(PersonnelModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     return Json(new {status = "success", message= "Thanks for the details"}); 
    } 
    else 
    { 
    var errors = new List<string>(); 
    foreach (var modelStateVal in ViewData.ModelState.Values) 
    { 
     errors.AddRange(modelStateVal.Errors.Select(error => error.ErrorMessage)); 
    } 
    return Json(new {status = "validationerror", errors = errors}); 
    } 
} 

、必ず私は2つのオーバーロードで@Html.ValidationSummary方法を使用して、空の文字列を渡すあなたのAJAXレスポンスJSONを処理するために、フォームを始める

@using (Ajax.BeginForm("Index", "Home", new AjaxOptions { OnSuccess = "OnSuccess", })) 
{ 
    @Html.ValidationSummary("", true) 
    @Html.TextBoxFor(model => model.MailAdress) 

    <!--Your other form input elements--> 
    <input type="submit" value="Html Form Action" /> 
} 

注成功ハンドラを持たせます最初のパラメーターとして。これにより、div内のul要素が常にvalidation-summary-validにレンダリングされます。

OnSuccess関数を作成してレスポンスを確認し、レスポンスにステータスプロパティがあり、その値がvalidationerrorであるかどうかを確認します。はいの場合は、エラーコレクションをループし、エラーのある新しいli要素を追加します。

function OnSuccess(response) { 
    var $summaryUl = $(".validation-summary-valid").find("ul"); 
    $summaryUl.empty(); 

    if (response.status === 'validationerror') { 
     $.each(response.errors, 
      function(a, b) { 
       $summaryUl.append($("<li>").text(b)); 
      }); 
    } else { 
     alert(response.message); 
    } 
} 
+0

ありがとうございました! –

関連する問題