2017-06-16 81 views
0

我在我的模型只接受數字的屬性上放了一些正則表達式。動態添加元素驗證錯誤

public class MaterialsViewModel 
    { 
     [Display(Name = "Material")] 
     public string MaterialName { get; set; } 
     [Range(typeof(int), "0", "999")] 
     [RegularExpression(@"^\d+$", ErrorMessage = "Please enter proper value")] 
     public int? Quantity { get; set; } 
     [RegularExpression(@"^\d+$", ErrorMessage = "Please enter proper value")] 
     public double? Cost { get; set; } 
     public IEnumerable<SelectListItem> CategoryList { get; set; } 

     public int SelectedCategory { get; set; } 
     public string SelectedCategoryName { get; set; } 
    } 

我有我的視圖中,我可以添加控件動態

Dynamically add ScopeOfWork and Materials<br /> 
    <div id="scopes"> 
     <h3>Scopes</h3> 
     <a href="javascript:void(0)" id="addScope">Add Scope of Work</a> 
     @for (int i = 0; i < Model.ScopeOfWork.Count; i++) 
     { 
      <div class="scope"> 
       <div class="form-group"> 
        @Html.LabelFor(m => m.ScopeOfWork[i].ScopeOfWorkName, htmlAttributes: new { @class = "control-label col-md-2" }) 
        <div class="col-md-10"> 
         @Html.TextBoxFor(m => m.ScopeOfWork[i].ScopeOfWorkName, new { @class = "form-control" }) 
         @Html.ValidationMessageFor(m => m.ScopeOfWork[i].ScopeOfWorkName) 
        </div> 
       </div> 
       <input type="hidden" class="scopeindex" name="ScopeOfWork.Index" value="@i" /> 
       <div class="indent materials"> 
        <h4>Material</h4> 
        <a href="javascript:void(0)" class="addmaterial">Add Material</a> 
        @for (int j = 0; j < Model.ScopeOfWork[i].Materials.Count; j++) 
        { 
         <div class="material"> 
          <div class="form-group"> 
           @Html.LabelFor(m => m.ScopeOfWork[i].Materials[j].MaterialName, htmlAttributes: new { @class = "control-label col-md-2" }) 
           <div class="col-md-2"> 
            @Html.TextBoxFor(m => m.ScopeOfWork[i].Materials[j].MaterialName, new { @class = "form-control" }) 
           </div> 
           <div class="col-md-10 col-md-offset-2"> 
            @Html.ValidationMessageFor(m => m.ScopeOfWork[i].Materials[j].MaterialName) 
           </div> 
          </div> 
          <div class="form-group"> 
           @Html.LabelFor(m => m.ScopeOfWork[i].Materials[j].Quantity, htmlAttributes: new { @class = "control-label col-md-2" }) 
           <div class="col-md-1"> 
            @Html.TextBoxFor(m => m.ScopeOfWork[i].Materials[j].Quantity, new { @class = "form-control" }) 
           </div> 
           <div class="col-md-10 col-md-offset-2"> 
            @Html.ValidationMessageFor(m => m.ScopeOfWork[i].Materials[j].Quantity) 
           </div> 
          </div> 
          <div class="form-group"> 
           @Html.LabelFor(m => m.ScopeOfWork[i].Materials[j].Cost, htmlAttributes: new { @class = "control-label col-md-2" }) 
           <div class="col-md-1"> 
            @Html.TextBoxFor(m => m.ScopeOfWork[i].Materials[j].Cost, new { @class = "form-control" }) 
           </div> 
           <div class="col-md-10 col-md-offset-2"> 
            @Html.ValidationMessageFor(m => m.ScopeOfWork[i].Materials[j].Cost) 
           </div> 
          </div> 
          <div class="form-group"> 
           <label class="control-label col-md-2">Category</label> 
           <div class="col-xs-2"> 
            @Html.DropDownListFor(m => m.ScopeOfWork[i].Materials[j].SelectedCategory, Model.ScopeOfWork[i].Materials[j].CategoryList, "Please select", htmlAttributes: new { @class = "form-control" }) 
           </div> 
          </div> 
          <input type="hidden" class="materialindex" name="ScopeOfWork[@i].Materials.Index" value="@j" /> 
         </div> 
        } 
       </div> 
      </div> 
     } 
    </div> 

    <div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input type="submit" value="Create" class="btn btn-success" /> 
     </div> 
    </div> 
</div> 
} 


<div id="newScope" style="display:none"> 
    <div class="scope"> 
     <div class="form-group"> 
      <label for="_#__ScopeOfWorkName" class="control-label col-md-2">Scope Of Work</label> 
      <div class="col-md-10"> 
       <input class="form-control" type="text" id="_#__ScopeOfWorkName" name="ScopeOfWork[#].ScopeOfWorkName" value=""> 
       <span class="field-validation-valid text-danger" data-valmsg-for="ScopeOfWork[#].ScopeOfWorkName" data-valmsg-replace="true"></span> 
      </div> 
     </div> 
     <input type="hidden" class="scopeindex" name="ScopeOfWork.Index" value="#" /> 
     <div class="materials"> 
      <h4>Material</h4> 
      <a href="javascript:void(0)" class="addmaterial">Add Material</a> 
     </div> 
     <hr /> 
    </div> 
</div> 

<div id="newMaterial" style="display:none"> 
    <div class="form-group"> 
     <label for="_#__Materials_%__MaterialName" class="control-label col-md-2">Material</label> 
     <div class="col-md-2"> 
      <input class="form-control" type="text" id="_#__Materials_%__MaterialName" name="ScopeOfWork[#].Materials[%].MaterialName" value=""> 
      <span class="field-validation-valid text-danger" data-valmsg-for="ScopeOfWork[#].Materials[%].MaterialName" data-valmsg-replace="true"></span> 
     </div> 
    </div> 

    <div class="form-group"> 
     <label for="_#__Materials_%__Quantity" class="control-label col-md-2">Quantity</label> 
     <div class="col-md-1"> 
      <input class="form-control" type="text" id="_#__Materials_%__Quantity" name="ScopeOfWork[#].Materials[%].Quantity" value=""> 
      <span class="field-validation-valid text-danger" data-valmsg-for="ScopeOfWork[#].Materials[%].Quantity" data-valmsg-replace="true"></span> 
     </div> 
    </div> 

    <div class="form-group"> 
     <label for="_#__Materials_%__Cost" class="control-label col-md-2">Cost</label> 
     <div class="col-md-1"> 
      <input class="form-control" type="text" id="_#__Materials_%__Cost" name="ScopeOfWork[#].Materials[%].Cost" value=""> 
      <span class="field-validation-valid text-danger" data-valmsg-for="ScopeOfWork[#].Materials[%].Cost" data-valmsg-replace="true"></span> 
     </div> 
    </div> 
    @*Drop down*@ 
    <div class="form-group"> 
     <label for="_#__Materials_%__SelectedCategory" class="control-label col-md-2">Category</label> 
     <div class="col-xs-2"> 
      <select class="form-control category" id="_#__Materials_%__SelectedCategory" name="ScopeOfWork[#].Materials[%].SelectedCategory"> 
       <option value="">--Select--</option> 
      </select> 
     </div> 
    </div> 

    <input type="hidden" class="materialindex" name="ScopeOfWork[#].Materials.Index" value="%" /> 
</div> 

<script> 
    var form = $('form'); 
    var scope = $('#newScope'); 
    var material = $('#newMaterial'); 
    var categories = @Html.Raw(Json.Encode(Model.CategoryList)); 

    form.on('click', '.addmaterial', function() { 
     var clone = material.clone(); 
     var scopeIndex = $(this).closest('.scope').find('.scopeindex').val(); 
     clone.html($(clone).html().replace(/#/g, scopeIndex)); 

     var materialIndex = new Date().getTime(); 
     clone.html($(clone).html().replace(/%/g, materialIndex)); 
     // drop down list 
     var select = clone.find('.category'); 
     $.each(categories, function(index, item) { 
      select.append($('<option></option>').val(item.Value).text(item.Text)); 
     }); 
     $(this).closest('.materials').append(clone.html()); 

     form.data('validator', null); 
     $.validator.unobtrusive.parse(form); 
    }); 

    $('#addScope').click(function() { 
     var clone = scope.clone(); 
     var scopeIndex = new Date().getTime(); 
     clone.html($(clone).html().replace(/#/g, scopeIndex)); 
     $('#scopes').append(clone.html()); 
     form.data('validator', null); 
     $.validator.unobtrusive.parse(form); 
    }); 
</script> 

控制器:

[HttpPost] 
     public ActionResult _CreateProject(ProjectViewModel project) 
     { 
      tblProject projectModel = new tblProject(); 
      tblScopeOfWork scopeModel = new tblScopeOfWork(); 
      tblMaterial materialModel = new tblMaterial(); 

      if (ModelState.IsValid) 
      { 
       projectModel.ProjectName = project.ProjectName; 
       projectModel.ProjectLocation = project.ProjectLocation; 
       projectModel.ProjectDescription = project.ProjectDescription; 
       projectModel.WorkArea = project.WorkArea; 
       projectModel.ModeOfPayment = project.ModeOfPayment; 
       projectModel.Duration = project.Duration; 
       projectModel.StartDate = project.StartDate; 
       projectModel.EndDate = project.EndDate; 
       projectModel.ProfitSupervision = project.ProfitSupervision; 
       projectModel.ProjectStatus = project.ProjectStatus; 
       projectModel.ForemanId = project.ForemanId; 
       projectModel.ClientId = project.ClientId; 

       db.tblProjects.Add(projectModel); 
       db.SaveChanges(); 

       //Get the recently created ProjectId 
       var recentProjectId = db.tblProjects.OrderByDescending(x => x.ProjectId).FirstOrDefault().ProjectId; 

       //Get all values from List of ScopeOfWork 
       //Add each ScopeOfWork to the database 
       for (int scopeIndex = 0; scopeIndex < project.ScopeOfWork.Count; scopeIndex++) 
       { 
        scopeModel = new tblScopeOfWork(); 
        scopeModel.ScopeOfWork = project.ScopeOfWork[scopeIndex].ScopeOfWorkName; 
        scopeModel.ProjectId = recentProjectId; 

        db.tblScopeOfWorks.Add(scopeModel); 
        db.SaveChanges(); 

        //Get the recently created ScopeOfWorkId 
        var recentScopeOfWorkId = db.tblScopeOfWorks.OrderByDescending(x => x.ScopeOfWorkId).FirstOrDefault().ScopeOfWorkId; 

        //Get all materials from its corresponding ScopeOfWork and save to database 
        for (int materialIndex = 0; materialIndex < project.ScopeOfWork[scopeIndex].Materials.Count; materialIndex++) 
        { 
         materialModel = new tblMaterial(); 
         materialModel.Description = project.ScopeOfWork[scopeIndex].Materials[materialIndex].MaterialName; 
         materialModel.Quantity = project.ScopeOfWork[scopeIndex].Materials[materialIndex].Quantity; 
         materialModel.Cost = project.ScopeOfWork[scopeIndex].Materials[materialIndex].Cost; 
         materialModel.ScopeOfWorkId = recentScopeOfWorkId; 
         materialModel.CategoryId = project.ScopeOfWork[scopeIndex].Materials[materialIndex].SelectedCategory; 
         db.tblMaterials.Add(materialModel); 
        } 
       } 
       db.SaveChanges(); 
      } 

      project.ScopeOfWork = new List<ScopeOfWorkViewModel> 
      { 
       new ScopeOfWorkViewModel() 
       { 
        Materials = new List<MaterialsViewModel> 
        { 
         new MaterialsViewModel() 
         { 
          CategoryList = new SelectList(db.tblCategories, "CategoryId", "CategoryName") 
         } 
        } 
       } 
      }; 
      return View(project); 
     } 
    } 

問題是,我試圖把對某個字符串( 'SS')文本框的數量和成本,看看驗證是否會起作用,並且出現The value 'ss' is not valid for QuantityThe value 'ss is not valid for Cost.,但它應該是Please enter proper value。而且無論何時驗證發生,Add Material鏈接都不能添加另一個newMaterial

我試過並檢查這些answerDotNetFiddle,但它仍然有一些錯誤。

回答

1

你不需要你的正則表達式(它的int,所以它只能接受一個數字)。和cost屬性一樣(但爲什麼如果你不允許小數部分,你爲什麼要把它做成十進制數?)。

該類型的驗證將首先執行,並且因爲該驗證無效,所以不會執行進一步的驗證。

更改屬性到一個[Required]

[Range(typeof(int), "0", "999")] 
[Required(ErrorMessage = "Please enter proper value")] 
public int? Quantity { get; set; } 

this question/answer參見用於改變默認的錯誤消息用於爲type一個無效值。

請注意,由於您尚未添加必要的data-val-*屬性,因此您的動態添加項目將不會提供客戶端驗證。您需要檢查爲for循環中的元素生成的html,並精確複製html,除了替換集合索引器。

您的POST方法也存在問題,因爲您將ScopeOfWork屬性設置爲新集合,並在返回視圖之前清除用戶輸入的所有數據。您的POST方法的基本結構應該是

[HttpPost] 
public ActionResult _CreateProject(ProjectViewModel project) 
{ 
    if (!ModelState.IsValid) 
    { 
     ConfigureViewModel(project); 
     return View(project); 
    } 
    // code to initialize your data models, save and redirect 
} 

private void ConfigureViewModel(ProjectViewModel model) 
{ 
    var categories = db.tblCategories; 
    model.CategoryList = new SelectList(categories , "CategoryId", "CategoryName"); 
    foreach (var scope in model.ScopeOfWork) 
    { 
     foreach (var material in scope.Materials) 
     { 
      material.CategoryList = new SelectList(categories , "CategoryId", "CategoryName"); 
     } 
    } 
} 

注意ConfigureviewModel()方法也從GET方法調用,用於填充SelectLists

+0

哦,我看到的,但仍當我點擊保存按鈕,它會返回我的觀點,但一旦我的觀點返回,我無法再添加一個新的材料,但我可以添加一個範圍。這是什麼原因? – progammer101

+0

給我一點時間來更詳細地研究你的代碼。我還將添加一個鏈接,顯示如何更改類型的默認消息。 –

+0

我也嘗試創建3沒有輸入的添加材料元素只是爲了檢查驗證和發佈它,一旦視圖是隻返回1添加材料元素顯示,而不是3. – progammer101