我正在關注此post。xVal - 僅爲ID字段生成規則
服務器端驗證按預期工作。但客戶端驗證器只能在ID字段中生成。
我的LINQ2SQL實體類有兩個屬性ID &類別名稱及以下是我的元數據類
[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生成驗證規則?我究竟做錯了什麼?
請根據您的最新評論將其標記爲已回答。謝謝。 – andymeadows 2009-08-14 18:13:11