2016-11-29 89 views
0

我想是能夠顯示驗證錯誤與我做了阿賈克斯後從MVC形式。所有的服務器驗證工作正常,但是當我發佈使用ajax後,我無法讓頁面顯示任何驗證錯誤。我已經看過其他答案在stackoverflow,但他們似乎令人費解,似乎這個問題必須已經解決了成千上萬次。MVC AJAX驗證與服務器屬性

這裏是我的C#服務器端瀏覽模式:

public class Card_TextViewModel:IValidatableObject 
     { 
      [Key] 
      [Required] 
      [StringLength(15, MinimumLength = 2)] 
      [Display(Name = "Product Code")] 
      [DataType(DataType.Text)] 
      public string Prod_Code { get; set; } 
      [Required] 
      [DataType(DataType.MultilineText)] 
      [Display(Name = "Page 1 Text")] 
      public string Page1Text { get; set; } 
      [Required] 
      [DataType(DataType.MultilineText)] 
      [Display(Name = "Inside Text")] 
      public string InsideText { get; set; } 
      [Display(Name = "User Name")] 
      [DataType(DataType.Text)] 
      public string UserName { get; set; } 
      [Display(Name = "Export Date")] 
      public DateTime? ExportDate { get; set; } 

      public IList<Card_Text> Card_Text { get; set; } 

      public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
      { 
       if(!string.IsNullOrEmpty(Prod_Code)) 
       { 
        if(string.IsNullOrWhiteSpace(Prod_Code.Substring(0,1))) 
        { 
         yield return new ValidationResult("The product code cannot start with a space", new[] { "Prod_Code" }); 
        } 
       } 
      } 
     } 

這裏是我的API代碼:

 public async Task<ActionResult> CreateAddExtra([Bind(Include = "Prod_Code,Page1Text,InsideText")] Card_TextViewModel viewModel) 
     { 
      try 
      { 
       if (!Request.IsAjaxRequest()) 
        return Json(new { success = false, message = "Request ajax request only" }); 

       if (!ModelState.IsValid) 
        return Json(new { success = false, message = "Invalid data" }); 

       Card_Text card_Text = await db.Card_Text.FindAsync(viewModel.Prod_Code); 

       if (card_Text != null) 
        return Json(new { success = false, message = string.Format("The product code {0} already exists", viewModel.Prod_Code) }); 

       card_Text = Mapper.Map<Card_TextViewModel, Card_Text>(viewModel); 
       card_Text.UserName = User.Identity.Name; 

       db.Card_Text.Add(card_Text); 

       if (await db.SaveChangesAsync() == 0) 
        return Json(new { success = true, message = string.Format("Error creating product code {0}", viewModel.Prod_Code) }); 

       return Json(new { success = true }); 
      } 
      catch (Exception exp) 
      { 
      } 

      return Json(new { success = false }); 
     } 

上述所有工作正常,並沒有出現問題,這裏是張貼的javascript在CreateAddExtra()

(function() { 
     $(document).ready(function() { 
      var successCount = 0; 

      var addCreate = function() { 
       var url = "https://localhost:44393/Card_Text/CreateAddExtra"; 
       var data = $("#create").serialize(); 

       $.post(url, data) 
        .done(function (data, textStatus, jqXHR) { 
         if (data.success === true) { 
          successCount++; 
          $('#successCount').text(successCount); 

         } else { 
          $.validator.unobtrusive.parse(document); 

          /*would like the unobtrusive javascript to display any valide errors that occurred on the post back, which are store in MVC ModelState 
How do we activate unobtrusive javascript? 
*/ 
        } 
       }); 

      return false; 
     }; 

//just event for a button press 
     $("#add").click(addCreate); 
    }); 
})(); 

這裏是MVC html頁面代碼:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "create" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

    <hr /> 

    <div class="form-group"> 
     @Html.LabelFor(model => model.Prod_Code) 
     @Html.EditorFor(model => model.Prod_Code, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.Prod_Code, "", new { @class = "text-danger" }) 
    </div> 

    <div class="form-group"> 
     @Html.LabelFor(model => model.Page1Text) 
     @Html.EditorFor(model => model.Page1Text, new { htmlAttributes = new { @class = "form-control", rows = 10, columns = 40 } }) 
     @Html.ValidationMessageFor(model => model.Page1Text, "", new { @class = "text-danger" }) 
    </div> 

    <div class="form-group"> 
     @Html.LabelFor(model => model.InsideText) 
     @Html.EditorFor(model => model.InsideText, new { htmlAttributes = new { @class = "form-control", rows = 10, columns = 40 } }) 
     @Html.ValidationMessageFor(model => model.InsideText, "", new { @class = "text-danger" }) 
    </div> 

    <div class="form-group"> 
     <input type="submit" value="Create" class="btn btn-primary" /> 
     <input type="submit" id="add" value="Add" class="btn btn-primary" /> 
     @Html.ActionLink("Back to List", "Index", "Card_Text", null, new { id = "recordCount", @class = "btn btn-default" }) 
    </div> 

    <div> 
     <span>Records added:</span> 
     <span id="successCount" class="text-danger">0</span> 
    </div> 
} 

因此,如果在回發時發生vaidation錯誤,我該如何激活不顯眼的javascript以向用戶顯示錯誤?

感謝您的時間

回答

1

我從這個link顯示一個簡單的技術來處理Ajax調用模型狀態錯誤了這個片段。

$(function() { 
    // hijax the form 
    $("form").submit(function (e) { 
     var $form = $(this); 
     var validator = $form.data("validator"); 

     if (!validator || !$form.valid()) 
      return; 

     e.preventDefault(); 

     $.ajax({ 
      url: "@Url.Action("index")", 
      type: "POST", 
      data: $form.serialize(), 
      statusCode: { 
       400: function(xhr, status, err) {       
        var errors = $.parseJSON(err); 
        validator.showErrors(errors); 
       } 
      }, 
      success: function() { 
       // just reload the page for now 
       location.reload(true); 
      } 
     }); 
    }); 

}); 
+0

羅斯您好,感謝您的時間。嘗試了上面的代碼片段,但代碼永遠不會達到,因爲行,如果(驗證|| $ form.valid()!)回報我的$就調用;它總是未定義的 – user142617