自定义 ViewModel 中属性声明的最佳实践是什么

发布于 2024-09-09 04:48:35 字数 867 浏览 2 评论 0原文

在我为应用程序构建的新 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城挽邺 2024-09-16 04:48:35

我不认为任何一种方式都“更好”,这实际上取决于对象本身。

如果 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 the User 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文