自定义 ViewModel 中属性声明的最佳实践是什么
在我为应用程序构建的新 UserViewModel 中,我有两个用于存储属性的选项。
第一个选项是
Public Property user As User ''# Including the entire User object
Public Property custString as String ''# Custom String for View
第二个选项是实际写出所有用户属性
Public Property ID As Integer ''# Declaring each object individually
Public Property UserName As String ''# Here is another object found in User
Public Property RegistrationDate As Date ''# Here is another object found in User
Public Property custStrin As String ''# Custom String for View
谁能告诉我更好的方法是什么以及为什么?
我目前有第一个选项,但是,与第二个选项相比,我不喜欢它在视图中的外观
这看起来不错(IMO)
<%: Model.UserName %>
这看起来不像很好(IMO)
<%: Model.User.UserName %>
In my new UserViewModel that I'm building for my application, I have two options for storing properties.
The first option is to have
Public Property user As User ''# Including the entire User object
Public Property custString as String ''# Custom String for View
The second option is to actually write out all the User properties
Public Property ID As Integer ''# Declaring each object individually
Public Property UserName As String ''# Here is another object found in User
Public Property RegistrationDate As Date ''# Here is another object found in User
Public Property custStrin As String ''# Custom String for View
Can anyone tell me what the better way to do this is and why?
I've currently got the first option, however, I don't like the way it looks in the View in comparison to the second option
This looks nice (IMO)
<%: Model.UserName %>
This does not look as nice (IMO)
<%: Model.User.UserName %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为任何一种方式都“更好”,这实际上取决于对象本身。
如果
User
对象具有仅获取属性、没有公共默认构造函数或复杂的状态逻辑,则它可能不适合由默认模型绑定直接设置。通常在这种情况下,您会“写出”User
属性的某些子集作为 ViewModel 的相应属性,然后 ViewModel 可以处理底层 User 对象的设置。这种情况并不少见。但是,如果您的
User
对象很简单并且可以直接绑定,那么直接将其用作模型的一部分肯定会更方便。I don't think either way is "better", it really depends on the objects themselves.
If the
User
object has get-only properties, no public default constructor, or complex state logic, it might not be a good candidate to be directly set by the default model binding. Usually in cases like that, you would "write out" some subset of theUser
properties as corresponding properties of the ViewModel, which can then handle the setup of the underlying User object. This scenario isn't uncommon.But if your
User
object is simple and is straightforward to bind to directly, then it's certainly more convenient to use it as part of your model directly.