Can I simplify this C# in my ViewModel?
-
26-02-2021 - |
Frage
In my code I have the following:
viewModel.Note.Modified = DateTime.Now;
viewModel.Note.ModifiedBy = User.Identity.Name;
and in my view:
[DisplayName("Modified")]
public DateTime Modified { get; set; }
[DisplayName("Modified By")]
public string ModifiedBy { get; set; }
Could I just have my code change ModifiedBy and then have some code that runs in the ViewModel that changes the date of Modified when the Modified by is changed?
Lösung
If viewModel.Note
is a reference to a NoteViewModel
instance, then you can use the following:
public class NoteViewModel{
private DateTime? m_Modified;
private string m_ModifiedBy;
// note that you do not need the DisplayNameAttribute, because the default
// display name is the property name
public DateTime Modified {
get { return m_Modified ?? DateTime.Now; }
}
[DisplayName("Modified By")]
public string ModifiedBy {
get { return m_ModifiedBy ?? string.Empty; }
set {
if(value!=null) {
m_ModifiedBy = value;
m_Modified = DateTime.Now;
}
}
}
}
Then in your "code" (I'm guessing you meant the controller?), you can just do:
viewModel.Note.ModifiedBy = User.Identity.Name;
and you will have the intended result.
Side Note: Depending on the audience of your application, you may want to consider using DateTime.UtcNow
for localization purposes. DateTime.Now
will return the current DateTime on the server, which is dependent on the server's location. If you are displaying this data to the user, it is likely that you will want to either (a) specify the time zone, or (b) localize the time to the time zone of the client machine
Andere Tipps
The way to do this will depend on how much logic you want in your view. If you don't mind some logic there, you can do something like this:
[DisplayName("Modified")]
public DateTime Modified { get; set; }
private string m_ModifiedBy
[DisplayName("Modified By")]
public string ModifiedBy {
get { return m_ModifiedBy; }
set{ m_ModifiedBy = value; Modified = DateTime.Now; }
}
If you want the logic in your ViewModel, you can do something like this: ( assuming that viewModel is a class variable )
public void SetModifiedBy(string modifiedBy) {
viewModel.Note.Modified = DateTime.Now;
viewModel.Note.ModifiedBy = modifiedBy;
}
Then you would just call SetModifiedBy(User.Identity.Name)
and both values would be updated.