0

我想在我的 ASP MVC 视图中给一个字段当前日期的默认值,但我不知道如何在视图代码中执行此操作。但是,我需要允许它成为可更新的字段,因为它并不总是最新的日期。有什么建议么?

    <div class="M-editor-label">
        Effective Date
    </div>
    <div class="M-editor-field">            
        @Html.EditorFor(model => model.EffectiveDate)
        @Html.ValidationMessageFor(model => model.EffectiveDate)
    </div>

编辑

我试图在模型中给这个字段一个默认值,就像这样

    private DateTime? effectiveDate = DateTime.Now;

    public Nullable<System.DateTime> EffectiveDate
    {
        get { return DateTime.Now; } 
        set { effectiveDate = value; }
    }

但是该get属性给了我以下错误消息:

Monet.Models.AgentTransmission.EffectiveDate.get must declare a body because it is not marked abstract extern or partial

^(Monet 是项目的名称,AgentTransmission 是我正在工作的当前模型的名称,其中 EffectiveDate 是一个属性。)

第二次编辑

根据以下答案之一中的建议,我将构造函数设置为这样,但是在呈现视图时,这仍然会在字段中放置一个空白值。

    public AgentTransmission()
    {
        EffectiveDate = DateTime.Now;
    }

第三次编辑

修复了上述问题get,发布了到目前为止我在控制器中的全部内容。

    public AgentTransmission()
    {
        EffectiveDate = DateTime.Today;
        this.AgencyStat1 = new HashSet<AgencyStat>();
    }

    //Have tried with an without this and got the same results
    private DateTime? effectiveDate = DateTime.Today;

    public Nullable<System.DateTime> EffectiveDate
    {
        get { return effectiveDate; }  
        set { effectiveDate = value; }
    }
4

2 回答 2

0

我会在模型类的构造函数中设置默认值。像这样的东西:

class YourClass {
  public DateTime EffectiveDate {get;set;}

  public YourClass() {
    EffectiveDate = DateTime.Today;
  }
}
于 2013-02-07T16:58:02.877 回答
0

正如其他答案所建议的那样,我通过在构造函数中创建一个默认值来解决这个问题,就像这样

public AgentTransmission()
{
    EffectiveDate = DateTime.Today;
    this.AgencyStat1 = new HashSet<AgencyStat>();
}

private DateTime? effectiveDate;

public Nullable<System.DateTime> EffectiveDate
{
    get { return effectiveDate; }  
    set { effectiveDate = value; }
}

并将此代码添加到构造函数中的特定页面以初始化新对象;

    public ActionResult Create()
    {
        return View(new AgentTransmission());
    } 
于 2013-02-07T17:44:45.107 回答