【问题标题】:Custom ViewModel Class - Not all fields are marked invalid unless a prefix is specified自定义 ViewModel 类 - 除非指定前缀,否则并非所有字段都标记为无效
【发布时间】:2009-08-14 11:11:17
【问题描述】:

我有一个自定义视图模型,其中有两个字段和一个 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);
    }
}

控制器中的 Create 动作如下所示:

[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 和 Field2 未标记为无效.. 没有添加到 css 类字段和不生成跨度标签用于视觉错误指示。

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

我在这里做错了什么?

抱歉把这篇文章写了这么久..

【问题讨论】:

  • 长篇文章没问题......信息很清楚并且需要。点赞!

标签: c# asp.net-mvc viewmodel data-annotations xval


【解决方案1】:

我认为问题可能是您的变量名和类名相同。

也许在你的 ViewModel 中重命名为,

public Book BookInstance { get; set; }

这需要进行一些重构,但我认为这是您的问题的原因。

善良,

【讨论】:

  • 不更改属性名称没有任何区别
猜你喜欢
  • 2022-01-18
  • 2019-04-19
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2019-01-30
相关资源
最近更新 更多