2015-05-09 96 views
0

我有一个视图,它创建一个主对象(作者)和其他对象(书籍)的列表。所以创建的对象可以通过调用author.Books.ToList()来返回书籍。ASP - EF 6只绑定复杂列表的某些属性?

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

我怎么告诉我要绑定author.Books框架[全部]请将.Name(和日期),但要放弃author.Books [全部]。价格? 我知道我可以在控制器中手动测试它,但我觉得有一个更好的解决方案,我不能完全把它放在手指上。

上下文的某些代码: 从视角的输入框:

<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 {...} 

(。在我的项目,我有不同的类具有相同的结构,所以它看起来愚蠢的创建笔者时产生的所有书籍)

回答

1

这正是我们需要的使用的ViewModels,

您可以在视图模型

刚刚成立
[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; 
} 

你可以阅读更多有关的ViewModels以及如何使用它们 herehere

+0

非常好的问题,我完全忽略了这一点,说明我还没有成长起来。谢谢你的准确答案。 –