Asp.net-Mvc
MVC 數據註釋範圍驗證無法正常工作
我的
RangeValidator模型中有一個屬性,只允許 0 到 100 之間的整數。我有一個部分視圖,顯示一個表單以通過 jQuery UI 對話框更新屬性。我查看了原始碼,可以確認數據註釋屬性正在正確生成。但是,驗證無法正常工作。它確實執行了某種驗證,但沒有使用我設置的範圍。值 1、10 和 100 不會產生錯誤。任何其他一位或兩位數的值都會產生錯誤。但是,如果我用零填充,所有小於 100 的值都可以。模型:
public class MyModel { ... [Required(ErrorMessage = "{0} is required")] [Range(typeof(int), "0", "100", ErrorMessage = "{0} can only be between {1} and {2}")] public int Percentage { get; set; } ... }局部視圖:
@model MyApp.Models.Partials.MyModel <div id="myDialog" class="editModal" title="Update Percentage"> @using (Ajax.BeginForm("UpdatePercentage", "MyController", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "onUpdateSuccess" }, new { name = "myForm" })) { @Html.ValidationSummary(null, new { style = "width:auto;max-width:22em; float:left;clear:both;" }) <div style="width:auto;float:left;clear:both;"> <div style="width:10em;float: left;text-align:right;clear:left;"> @Html.Label("Percentage:") </div> <div style="width:12em;margin-left:1em;float:left;clear:right;"> @Html.TextBoxFor(m => m.Percentage) </div> </div> <div style="width:23em;clear:both;text-align:center;"> <hr /> <input type="button" value="Cancel" class="cancelModalButton" data-modal="myDialog" /> <input type="submit" value="Submit" class="submitModalButton" data-modal="myDialog" data-form="myForm" /> </div> } </div>產生的標記:
<div id="myDialog" class="editModal" title="Update Percentage"> <form action="/Web/MyController/UpdatePercentage?Length=3" data-ajax="true" data-ajax-method="Post" data-ajax-success="onUpdateSuccess" id="form2" method="post" name="myForm"> <div class="validation-summary-valid" data-valmsg-summary="true" style="width:auto;max-width:22em;float:left;clear:both;"> <ul> <li style="display:none"></li> </ul> </div> <div style="width:auto;float:left;clear:both;margin-bottom:.75em;"> <div style="width:10em;float: left;text-align:right;clear:left;"> <label for="Percentage:">Percentage:</label> </div> <div style="width:12em;margin-left:1em;float:left;clear:right;"> <input data-val="true" data-val-number="The field Percentage must be a number." data-val-range="Percentage can only be between 0 and 100" data-val-range-max="100" data-val-range-min="0" data-val-required="Percentage is required" id="Percentage" name="Percentage" type="text" value="10" /> </div> </div> <div style="width:23em;clear:both;text-align:center;"> <hr /> <input type="button" value="Cancel" class="cancelModalButton" data-modal="myDialog" /> <input type="submit" value="Submit" class="submitModalButton" data-modal="myDialog" data-form="myForm" /> </div> </form> </div>我看到類型設置為
text,如果我TextBoxFor將EditorFor其更改為 ,number但我仍然看到相同的行為。
我遇到了這個確切的問題,並在這裡找到了解決方案。您需要升級以下內容:
jQuery Validation(至少 1.11.1)
Microsoft jQuery Unobtrusive Validation(至少 2.0.30116.0)
Microsoft jQuery Unobtrusive Ajax(至少 2.0.30116.0)
該問題是由 jQuery 1.9.1 中的重大更改引入的