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はプロパティです。)

2番目の編集

以下の回答の1つにある提案に従って、コンストラクターをそのように設定しましたが、ビューがレンダリングされたときに、フィールドに空白の値が入力されました。

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

3番目の編集

上記の問題を修正し、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 に答える