自定义 ViewModel 类 - 除非指定前缀,否则并非所有字段都标记为无效
我有一个自定义视图模型,其中有两个字段和一个 linq2sql 实体。所有字段都附加了验证属性。 即使所有字段都无效,只有 linq2sql 类中的字段会以可视方式指示错误,并且视图模型中的字段会正常显示。 但所有无效字段都会显示错误消息。
我的自定义 ViewModel 如下所示:
public class BooksViewModel
{
public SelectList BookCategories { get; set; }
public Book Book { get; set; }
[Required(ErrorMessage="Field1 is required")]
[StringLength(10)]
public string Field1 { get; set; }
[Required(ErrorMessage = "Field2 question is required")]
[StringLength(100)]
public string Field2 { get; set; }
}
Book 类是一个 linq2sql 实体,它附加了用于验证的元数据类型属性。
[MetadataType(typeof(BookMetadata))]
public partial class Book
{
}
public class BookMetadata
{
[Required(ErrorMessage="Choose a category")]
public int CategoryID { get; set; }
[Required(ErrorMessage = "Title is required")]
[StringLength(100)]
public string Title { get; set; }
[Required(ErrorMessage = "Published date is required")]
[DataType(DataType.Date, ErrorMessage="Enter a valid date")]
public DateTime PublishedDate { get; set; }
[Required(ErrorMessage = "Author is required")]
[StringLength(50)]
public string Author { get; set; }
}
存储库中有一个 AddBook 方法,有两个重载。 一个采用视图模型,一个采用 Book 类型:
public void AddBook(Book book)
{
var errors = DataAnnotationsValidationRunner.GetErrors(book);
if (errors.Any()) {
throw new RulesException(errors);
}
_db.Books.InsertOnSubmit(book);
_db.SubmitChanges();
}
public void AddBook(BooksViewModel model)
{
var errors = DataAnnotationsValidationRunner.GetErrors(model);
if (errors.Any()) {
throw new RulesException(errors);
}
}
控制器中的创建操作如下所示:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Book.ID")]BooksViewModel booksViewModel)
{
try {
// Validate Book
_repository.AddBook(booksViewModel.Book);
} catch(RulesException ex) {
ex.AddModelStateErrors(ModelState, "Book");
}
try {
// Validate other fields in the view model
_repository.AddBook(booksViewModel);
} catch (RulesException ex) {
ex.AddModelStateErrors(ModelState, "");
}
if (ModelState.IsValid) {
return RedirectToAction("Index");
} else {
booksViewModel.BookCategories = new SelectList(_repository.GetAllCategories().AsEnumerable(), "ID", "CategoryName", booksViewModel.Book.CategoryID);
return (ActionResult)View(booksViewModel);
}
}
我正在使用 xVal 生成客户端验证规则..我的创建视图如下所示:
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Book.CategoryID">CategoryID:</label>
<%= Html.DropDownList("Book.CategoryID", Model.BookCategories, "Select")%>
<%= Html.ValidationMessage("Book.CategoryID", "*")%>
</p>
<p>
<label for="Book.Title">Title:</label>
<%= Html.TextBox("Book.Title")%>
<%= Html.ValidationMessage("Book.Title", "*")%>
</p>
<p>
<label for="Book.PublishedDate">PublishedDate:</label>
<%= Html.TextBox("Book.PublishedDate")%>
<%= Html.ValidationMessage("Book.PublishedDate", "*")%>
</p>
<p>
<label for="Book.Author">Author:</label>
<%= Html.TextBox("Book.Author")%>
<%= Html.ValidationMessage("Book.Author", "*")%>
</p>
<p>
<label for="Field1">Field1:</label>
<%= Html.TextBox("Field1")%>
<%= Html.ValidationMessage("Field1", "*")%>
</p>
<p>
<label for="Field2">Field2:</label>
<%= Html.TextBox("Field2")%>
<%= Html.ValidationMessage("Field2", "*")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
<%= Html.ClientSideValidation<BooksViewModel>() %>
<%= Html.ClientSideValidation<Book>("Book") %>
客户端验证工作正常..但是如果我关闭 javascript,然后回发表单,除了 Field1 和 Field1 之外的所有字段都会显示错误消息。 Field2 未标记为无效。没有向字段添加 css 类,也没有生成用于视觉错误指示的 span 标记。
截图http://img22.imageshack.us/img22/324/26677634.jpg
但是,如果我用任何东西修复 ViewModel 字段
public ActionResult Create([Bind(Prefix = "VM", Exclude = "Book.ID")]BooksViewModel booksViewModel)
并相应地修改视图,那么一切都会正常:
<p>
<label for="VM.Book.Title">Title:</label>
<%= Html.TextBox("VM.Book.Title")%>
<%= Html.ValidationMessage("VM.Book.Title", "*")%>
</p>
<p>
<label for="VM.Field1">Field1:</label>
<%= Html.TextBox("VM.Field1")%>
<%= Html.ValidationMessage("VM.Field1", "*")%>
</p>
<%= Html.ClientSideValidation<BooksViewModel>("VM") %>
<%= Html.ClientSideValidation<Book>("Book") %>
我在这里做错了什么?
抱歉让这篇文章写得这么长..
I have a custom viewmodel inside which I have two fields and one linq2sql entity .. all fields have Validation Attributes attached. Even if all fields are invalid only the fields in the linq2sql class are visually indicated for error and fields in the viewmodel are displayed normally. But the error messages are displayed for all invalid fields.
My Custom ViewModel looks like this:
public class BooksViewModel
{
public SelectList BookCategories { get; set; }
public Book Book { get; set; }
[Required(ErrorMessage="Field1 is required")]
[StringLength(10)]
public string Field1 { get; set; }
[Required(ErrorMessage = "Field2 question is required")]
[StringLength(100)]
public string Field2 { get; set; }
}
The Book class is a linq2sql entity which has a metadatatype attribute attached for validation.
[MetadataType(typeof(BookMetadata))]
public partial class Book
{
}
public class BookMetadata
{
[Required(ErrorMessage="Choose a category")]
public int CategoryID { get; set; }
[Required(ErrorMessage = "Title is required")]
[StringLength(100)]
public string Title { get; set; }
[Required(ErrorMessage = "Published date is required")]
[DataType(DataType.Date, ErrorMessage="Enter a valid date")]
public DateTime PublishedDate { get; set; }
[Required(ErrorMessage = "Author is required")]
[StringLength(50)]
public string Author { get; set; }
}
There is a AddBook method in the repository with two overloads. One takes the viewmodel and one takes a Book type:
public void AddBook(Book book)
{
var errors = DataAnnotationsValidationRunner.GetErrors(book);
if (errors.Any()) {
throw new RulesException(errors);
}
_db.Books.InsertOnSubmit(book);
_db.SubmitChanges();
}
public void AddBook(BooksViewModel model)
{
var errors = DataAnnotationsValidationRunner.GetErrors(model);
if (errors.Any()) {
throw new RulesException(errors);
}
}
The Create action in the controller looks like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Book.ID")]BooksViewModel booksViewModel)
{
try {
// Validate Book
_repository.AddBook(booksViewModel.Book);
} catch(RulesException ex) {
ex.AddModelStateErrors(ModelState, "Book");
}
try {
// Validate other fields in the view model
_repository.AddBook(booksViewModel);
} catch (RulesException ex) {
ex.AddModelStateErrors(ModelState, "");
}
if (ModelState.IsValid) {
return RedirectToAction("Index");
} else {
booksViewModel.BookCategories = new SelectList(_repository.GetAllCategories().AsEnumerable(), "ID", "CategoryName", booksViewModel.Book.CategoryID);
return (ActionResult)View(booksViewModel);
}
}
I am using xVal to generate client side validation rules .. My create view looks like this:
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Book.CategoryID">CategoryID:</label>
<%= Html.DropDownList("Book.CategoryID", Model.BookCategories, "Select")%>
<%= Html.ValidationMessage("Book.CategoryID", "*")%>
</p>
<p>
<label for="Book.Title">Title:</label>
<%= Html.TextBox("Book.Title")%>
<%= Html.ValidationMessage("Book.Title", "*")%>
</p>
<p>
<label for="Book.PublishedDate">PublishedDate:</label>
<%= Html.TextBox("Book.PublishedDate")%>
<%= Html.ValidationMessage("Book.PublishedDate", "*")%>
</p>
<p>
<label for="Book.Author">Author:</label>
<%= Html.TextBox("Book.Author")%>
<%= Html.ValidationMessage("Book.Author", "*")%>
</p>
<p>
<label for="Field1">Field1:</label>
<%= Html.TextBox("Field1")%>
<%= Html.ValidationMessage("Field1", "*")%>
</p>
<p>
<label for="Field2">Field2:</label>
<%= Html.TextBox("Field2")%>
<%= Html.ValidationMessage("Field2", "*")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
<%= Html.ClientSideValidation<BooksViewModel>() %>
<%= Html.ClientSideValidation<Book>("Book") %>
the client side validation work fine .. but if I turn off javascript and then post back the form error message are displayed for all fields but the Field1 & Field2 are not marked as invalid .. there is no css class added to the fields and no span tags are generated for visual error indication.
Screenshot http://img22.imageshack.us/img22/324/26677634.jpg
But if I pefix the ViewModel fields with anything
public ActionResult Create([Bind(Prefix = "VM", Exclude = "Book.ID")]BooksViewModel booksViewModel)
And modify the view accordingly then everything works fine:
<p>
<label for="VM.Book.Title">Title:</label>
<%= Html.TextBox("VM.Book.Title")%>
<%= Html.ValidationMessage("VM.Book.Title", "*")%>
</p>
<p>
<label for="VM.Field1">Field1:</label>
<%= Html.TextBox("VM.Field1")%>
<%= Html.ValidationMessage("VM.Field1", "*")%>
</p>
<%= Html.ClientSideValidation<BooksViewModel>("VM") %>
<%= Html.ClientSideValidation<Book>("Book") %>
What am I doing wrong here?
Sorry for making this post so long ..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题可能是你的变量名和类名相同。
也许在您的 ViewModel 中重命名为类似的内容,
这需要进行一些重构,但我认为这是问题的原因。
善良,
丹
I think the problem might be your variable name and class name are identical.
Perhaps in your ViewModel rename to something like,
That'll require a bit of a refactor through, but I think it is the cause of your issue.
Kindness,
Dan