ASP - EF 6 仅绑定复杂列表的某些属性?

ASP - EF 6 bind only certain properties of a complex list?

我有一个视图,它创建一个主要对象(作者)和它的其他对象列表(书籍)。例如,创建的对象可以通过调用 author.Books.ToList() return 书籍。

我的问题是我只希望用户能够设置图书的某些属性(名称、日期等)。我不希望他们能够使用 javascript 注入表格并设置一本书的价格。

如何告诉框架我想绑定 author.Books[all].Name(和日期),但想丢弃 author.Books[all].Price? 我知道我可以在控制器中手动测试它,但我觉得有更好的解决方案,但我无法完全理解它。

上下文的一些代码: 来自视图的输入框:

<input data-val="true" data-val-required="The CanBeBorrowed field is required." id="books_0__CanBeBorrowed" name="books[0].CanBeBorrowed" type="checkbox" value="true"`>

您可以看到添加额外的输入字段会如何破坏数据。 控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Name,Date,Books")]Author author {...}

(在我的项目中,我有不同的 类 具有相同的结构。这就是为什么在创建作者时创建所有书籍看起来很愚蠢。)

这正是我们需要使用 ViewModel 的原因,

您可以在 ViewModel 中设置

[Editable(false)]
public decimal Price { get; set; }

还有你的

[HttpPost]
[ValidateAntiForgeryToken]
    public ActionResult Create([AuthorViewModel authorVm)
{
      var author = _repository.getById(authorVm.Id);
      //update only the fields of author object that user is allowed to   update.
      author.Name = authorVm.Name;
      author.Date = authorVm.Date;
}

您可以阅读有关 ViewModel 以及如何使用它们的更多信息 here and here