我正在关注这篇文章。
服务器端验证按预期工作。但是客户端验证器只会为 ID 字段生成。
我的 Linq2Sql 实体类有两个属性 ID 和 CategoryName,下面是我的元数据类
[MetadataType(typeof(BookCategoryMetadata))]
public partial class BookCategory{}
public class BookCategoryMetadata
{
[Required]
[StringLength(50)]
public string CategoryName { get; set; }
}
添加类别的方法
/// <summary>
/// Adds the category.
/// </summary>
/// <param name="category">The category.</param>
public void AddCategory(BookCategory category)
{
var errors = DataAnotationsValidationHelper.GetErrors(category);
if (errors.Any()) {
throw new RulesException(errors);
}
_db.BookCategories.InsertOnSubmit(category);
_db.SubmitChanges();
}
在控制器中创建动作
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "ID")]BookCategory category)
{
try {
_repository.AddCategory(category);
} catch (RulesException ex) {
ex.AddModelStateErrors(ModelState, "");
}
return ModelState.IsValid ? RedirectToAction("Index") : (ActionResult)View();
}
和视图
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="CategoryName">CategoryName:</label>
<%= Html.TextBox("CategoryName") %>
<%= Html.ValidationMessage("CategoryName", "*") %>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
<%= Html.ClientSideValidation<BookCategory>() %>
现在 xVal 只为 ID 字段生成验证规则。
<script type="text/javascript">xVal.AttachValidator(null, {"Fields":[{"FieldName":"ID","FieldRules":[{"RuleName":"DataType","RuleParameters":{"Type":"Integer"}}]}]})</script>
CategoryName 的服务器端验证工作完美。为什么 xVal 不为 CategoryName 生成验证规则?我究竟做错了什么?