Assign current date to a property in MVC

2019-06-08 16:42发布

问题:

I am creating a model for users and I want that property joined was set to Now(). Here's my code:

[DefaultValue(DateTime.Now)]
public DateTime joined {get; set;}

I get error:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

What am I doing wrong? And what's the best way to do what I want?

回答1:

DateTime.Now is not a constant, but a property that's computed at runtime, which is why you can't do what you're suggesting.

You can do what you're proposing with either:

public class MyClass {
  public DateTime joined { get; set; }
  public MyClass() {
    joined = DateTime.Now;
  }
}

Or:

public class MyClass {
  private DateTime _joined = DateTime.Now;
  public DateTime joined { get { return _joined; } set { _joined = value; } }
}


回答2:

You could try this in your model class:

private DateTime _joined = DateTime.Now;
public DateTime Joined 
{
  get { return _joined; }
  set { _joined = value; }
}


回答3:

You can not set expressions to the default value attribute. Because dataannotaions are not runtime attributes. You should set default value by like this

private DateTime _joined = DateTime.Now;
public DateTime Joined 
{
  get { 
      return _joined; 
  }
  set { 
      _joined = value; 
  }
}


回答4:

You can do it like what the others suggest, but another alternative is to set it in your action method, after your mapping from view model to domain and just before adding it to the database (if this is what you need to do):

[HttpPost]
public ActionResult Create(YourViewModel viewModel)
{
     // Check if view model is not null and handle it if it is null

     // Do mapping from view model to domain model
     User user = ...  // Mapping
     user.DateJoined = DateTime.Now;

     // Do whatever else you need to do
}

Your domail model for user:

public class User
{
     // Other properties here

     public DateTime DateJoined { get; set; }
}

I personally would have set it in the action method because the date and time would be more closer to when the user is actually added to the database (assuming this is what you wanted to do). Let says you create your user object at 12:00 then this will be your time when the user is added to the database, but what if you only click the submit button at 12:30? I would much rather prefer 12:30 than 12:00.