What are Best Practices for Property Declaration in a Custom ViewModel
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 %>
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.
精彩评论