我有一個RangeValidator
在我的模型屬性只允許整數介於0和100之間。我有一個局部視圖,顯示一個表單通過jQuery UI對話框更新屬性。我查看了源代碼並可以確認正在生成數據註釋屬性。但是,驗證工作不正常。它確實執行某種驗證,但它沒有使用我設置的範圍。值1,10和100不會產生錯誤。任何其他單個或兩位數值都會產生錯誤。但是,如果我使用零填充,則所有小於一百的值都可以。MVC數據註釋範圍驗證工作不正常
型號:
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
它chnages到number
但我仍然看到相同的行爲。
這是一個突破對jQuery的更改的問題,請參閱:http://stackoverflow.com/questions/14889431/client-side-validation-trips-on-dataannotation -range-attribute – felickz 2013-06-05 22:17:17