使用 MVC.NET 模型绑定,视图页面模型和绑定模型必须是同一个类吗?
(也就是说,您传递给视图的模型以及表单发布后返回的模型。)
如果不是,那么这样做是否更好?如果您正在收集的数据超出了视图页面模型的属性范围,该怎么办?
(That is, the model that you pass to the view and the model that you get back once the form posts.)
If not, is it better to do so anyways? What if there is data you are gathering that is beyond what the view page model has a property for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对这个问题有点不清楚,如果我错了,请纠正我。我假设您正在谈论传递给视图的模型以及表单发布后返回的模型。
不,它们不必相同,但可能会有相当多的重叠。进入视图的模型应包含发布模型所需的所有字段,因为如果存在验证错误,您需要发送备份数据。
我的模型是相同的,原因是我使用的模型通常只包含与表单上的元素相对应的属性。如果我需要额外的数据,也许是页面标题,我通常会将其直接添加到 ViewData。
如果模型类上有额外的属性,并且在 Post 上使用自动绑定,则会遇到这样的问题:如果有人在传输过程中修改 Post 请求并添加与模型中未使用的属性相对应的额外数据,则您将拥有自动绑定器绑定在最坏的情况下,这些数据可能会被用于 SQL 注入攻击(最好的情况是您的应用程序处于未知状态)。所以我的建议是不要这样做。如果您绝对必须这样做,假设您有基于页面上其他一些元素显示和隐藏的字段,请使用手动绑定,并且不要绑定不应包含数据的字段。
I am a little unclear about the question, so correct me if I am wrong. I am assuming that you are talking about the model that you pass to the view and the model that you get back once the form posts.
No they don't have to be the same, you would probably have a fair bit of overlap though. The model going up to the view should contain all the fields that the Post one would as you would need to send the data back up if there were validation errors.
My models are the same, the reason is that the models I use usually contain only the properties corresponding to the elements on the form. If I need extra data, perhaps a page title, I would typically add that directly to ViewData.
If you have extra properties on the model class and you use automatic binding on Post, you have the issue where if someone modifies the Post request in transit and adds extra data corresponding to the unused properties in the model, you would have the automatic binder bind that data which in the worst case could be used for something like a SQL Injection attack (best case is your app is in an unknown state). So my advice is don't do that. If you absolutely must, say you have fields that get shown and hidden based on some other elements up the page, use manual binding and don't bind fields that shouldn't have data in them.
当然,您可以在控制器的参数中使用与发送到视图的参数不同的类,这通常非常有用。例如,我经常在表单中将父实体传递给视图,但视图回发一个表单,其中包含将成为子实体的新实例的内容。您也可以处理来自客户端的其他字段。
模型绑定具有处理排除尝试从绑定加载的绑定类中的属性的属性,
这是一个示例:
Sure you can use different classes in the controller's parameters than the one you send to the view, and that can often be quite useful. For example, I often have forms where I'm passing in a parent entity to the view, but the view is posting back a form that contains stuff that will become a new instance of a child entity. You can handle additional fields from the client too.
Model binding has attributes that deal with excluding properties in a bound class from attempting to load from binding
Here is an example: