C# 自定义ViewModel类-除非指定前缀,否则并非所有字段都标记为无效

C# 自定义ViewModel类-除非指定前缀,否则并非所有字段都标记为无效,c#,asp.net-mvc,viewmodel,data-annotations,xval,C#,Asp.net Mvc,Viewmodel,Data Annotations,Xval,我有一个自定义viewmodel,其中有两个字段和一个linq2sql实体。。所有字段都附加了验证属性。即使所有字段都无效,也只有linq2sql类中的字段会直观地显示错误,并且viewmodel中的字段会正常显示。但所有无效字段都会显示错误消息 我的自定义ViewModel如下所示: public class BooksViewModel { public SelectList BookCategories { get; set; } public Book Book { g

我有一个自定义viewmodel,其中有两个字段和一个linq2sql实体。。所有字段都附加了验证属性。即使所有字段都无效,也只有linq2sql类中的字段会直观地显示错误,并且viewmodel中的字段会正常显示。但所有无效字段都会显示错误消息

我的自定义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; }
}
[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);
    }
}
<% 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") %>
Book类是一个linq2sql实体,它附加了一个metadatatype属性以进行验证

[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方法。一个采用viewmodel,另一个采用书本类型:

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);
    }
}
控制器中的创建操作如下所示:

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; }
}
[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);
    }
}
<% 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") %>
我正在使用xVal生成客户端验证规则。。我的创建视图如下所示:

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; }
}
[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);
    }
}
<% 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") %>
并相应地修改视图,然后一切正常:

<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") %>

标题:

字段1:

我做错了什么


很抱歉让这篇文章这么长。

我想问题可能是您的变量名和类名相同

也许在您的ViewModel中重命名为

public Book BookInstance { get; set; }
这需要一点重构,但我认为这是问题的原因

善良


Dan

一个长帖子没问题。。。信息是清楚的,是需要的。向上投票!不更改属性名称没有任何区别