我应该只对两个对象使用视图模型吗?
假设我有一个接受 Person
对象的视图。
具有三个属性:FirstName
、LastName
、Age
现在假设我添加了另一个不属于该对象的文本框字段。
我不需要文本框的值,它只是填充了供用户使用的数据。
当您编辑字段并将 Person
发布到控制器时,我们假设存在验证问题,因此您返回 Person 对象并返回错误。
问题是现在附加文本框已丢失其值,因为它不是模型的一部分。
因此,我创建了一个 ViewModel,其中包含该字段的字符串属性和一个 Person 属性来保留所有值。似乎有更好的方法将值保留在“特殊”文本框中?
Lets say I have a view that accepts a Person
object.
Has three properties, FirstName
, LastName
, Age
Now lets say I add another textbox field that's not part of the object.
I don't need the value of the textbox, its just populated with data that's for the user.
When you edit the fields and post the Person
to the controller, lets assume there is a validation problem so you return the Person object back with Errors
The problem is now the additional textbox has lost it's value since its not part of the model.
So I made a ViewModel with a string property for that field and a Person property to keep all the values. Seems like there would be a better way to keep the value in the "special" textbox?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该能够从发布的字段中获取该额外字段。第一次通过 ViewBag 如何设置?您应该可以再次设置它。
但是使用 ViewModel 到底有什么问题呢?迟早您将拥有 2 或 3 个额外字段,或者一个人和一个约会。
You should be able to get that extra field from the posted fields. How do you set it first time, through the ViewBag? You should be able to set it again.
But what exactly is wrong with using a ViewModel? Sooner or later you will have 2 or 3 extra fields, or a Person and an Appointment.
我认为这是完全正确的做法。 viewmodel 是视图的模型,而不是非 UI 处理的模型,它包含一个 Person 和额外的可视信息。它完全符合这个概念。您的人员大概是一个(非视图)模型,因此当您有有效的回发时,您可以让人员保存其数据(或其他内容),并且此时额外的可见信息是无关紧要的,因为您不再在应用程序的“视图/UI”部分。
使视图强类型化到您的视图模型并访问其中的人员
使用视图模型,比 ViewBags/Session/ViewData 等干净得多。
I think that's totally the right way to do it. The viewmodel is the model for the view not the model for your non-UI processing, it contains a Person and extra viewable information. It fits exactly with the concept. Your Person is presumably a (non-view) model and therefore when you have a valid post back, you get the Person to save it's data (or whatever) and the extra viewable information is irrelevant at that point, because you are no longer in a 'View/UI' part of your app.
Make the view strongly typed to your viewmodel and access the Person within it
Go with the viewmodel, so much cleaner than ViewBags/Session/ViewData etc.
很多时候,您可能认为不需要包含到 ViewModel 的 UI 映射,但大多数时候您最终会将映射添加到 ViewModel 中。我相信 ViewModel 应该代表 UI 屏幕上的所有内容。由于 HTTP 是无状态的,因此发布表单值将在填充用户界面控件中发挥重要作用。
There are many times that you might think that you do not need to include a UI mapping to a ViewModel but most of the time you will end up adding the mapping into the ViewModel. I believe that ViewModel should represent everything on your UI screen. Since HTTP is stateless the post form values will play an important role in populating the user interface controls.