2017-09-18 43 views
0

我有一個視圖,其中項目(模型視圖)使用BeginCollectionItem和partialview動態創建/刪除。動態創建的視圖的驗證不會觸發。 代碼: 的MainView:使用動態創建的PartialViews時,驗證不起作用mvc5

​​

PartialView:

@model EnquiryLineItemVM 

<div class="editorRow"> 
    @using (Html.BeginCollectionItem("ItemList")) 
    { 
     <table class="table"> 

      @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

      <tr> 
       <td> 
        @Html.EditorFor(model => model.ItemDesc) 
        @Html.ValidationMessageFor(model => model.ItemDesc, "", new { @class = "text-danger" }) 
       </td> 
       <td> 
        @Html.EditorFor(model => model.Quantity) 
        @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" }) 
       </td> 

       <td> 
        @Html.DropDownListFor(model => model.ManufacturerId, Model.ManufacturerList, "--Please Select--") 
        @Html.ValidationMessageFor(model => model.ManufacturerId, "", new { @class = "text-danger" }) 
       </td> 
       <td> 

        <a href="#" class="deleteRow">Delete</a> 
       </td> 
      </tr> 
     </table> 

    } 
    </div> 

視圖模型:

public class EnquiryLineItemVM 
    { 
     public int ID { get; set; } 
     [Required] 
     public string ItemDesc { get; set; } 
     [Required] 
     public int Quantity { get; set; } 

    } 

類似的問題,它使用的驗證在這樣的情況在這裏SO1但沒有奏效。我在視圖中引用了不顯眼的Jquery驗證。 請幫忙。謝謝閱讀 。

+0

[局部視圖,通過使用Html.BeginCollectionItem助手的集合(可能的重複https://stackoverflow.com/questions/40539321/a-partial-view-passing-a-collection-using-html-begincollectionitem-helper) –

+0

您需要在添加新項目的html後重新分析驗證器。即成功回調 - 就像你鏈接到的答案一樣(它確實有效)。您目前只在頁面被渲染爲無意義的時候才這樣做。 –

+0

而你仍然沒有修復你在[上一個問題]中提到的所有其他錯誤(https://stackoverflow.com/questions/46277135/using-begincollectionitem-for-adding-deleting-lineitems-in-mvc5- partialview) –

回答

1

當您動態添加到DOM時,Jquery驗證不起作用,因爲它添加了驗證中使用的屬性。解決方法是再次調用它,你加載後:

$('#addItem').on('click', function() { 
    $.ajax({ 
     url: '@Url.Action("CreateLineItem")', 
      cache: false, 
      success: function (html) { 
          $("#editorRowsLineitems").append(html); 
          // clear and add validation attributes 
          $("form").removeData("validator"); 
          $("form").removeData("unobtrusiveValidation"); 
          $.validator.unobtrusive.parse("form"); 
         } 
     }); 
     return false; 
    }); 

here

+0

感謝您指出這一點。我已經將驗證器刪除腳本放在了成功功能之外。它現在有效。 – user2695433