簡體   English   中英

如何使用DateTime.Now自動創建實體,而不是由用戶指定值?

[英]How do I create an Entity automatically with DateTime.Now, instead of the user specify the value?

使用ASP.NET MVC4,我有一個CreateView,用戶在其中指定Author,Text和CreateTime。 我不希望用戶看到或填寫CreateTime,我希望我的代碼使用DateTime.Now.ToShortDateTime()在此處自動執行此操作。

這是我想碰到的CreateView中的這一部分。

@Html.EditorFor(model => model.CreateTime)

編輯:這是我的CreateView:

@model Models.Topic


@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Topic</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Author)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Author)
            @Html.ValidationMessageFor(model => model.Author)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CreateTime)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CreateTime)
            @Html.ValidationMessageFor(model => model.CreateTime)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

通過html幫助器創建隱藏的輸入:

@Html.HiddenFor(model => model.CreateTime)

您可以設置編輯器的默認值

@Html.EditorFor( model => model.CreateTime, 
                                        new { @Value = DateTime.Now.ToShortDateString() })

如果您不希望用戶設置任何內容,請不要在HTML上放置隱藏字段或其他任何地方。

最好在行動方法發布后排除

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult  FormPostAction([Bind(Exclude = "CreateTime")] Topic topic)
{
and here you have to initialize CreateTime with whatever value you want...
}

首先定義一個接口

public interface ICreatedTracked
{
     DateTime CreateTime {get;set;}
}

然后,您就可以從中繼承所有跟蹤的模型,即:

public class SomeModel : ICreatedTracked
{
... your properties
public DateTime CreateTime {get;set;}
}

然后,您可以像這樣在DbContext上覆蓋SaveChanges:

public override int SaveChanges()
    {
    IEnumerable<DbEntityEntry<ICreatedTracked>> timeStampedEntities = ChangeTracker.Entries<ICreatedTracked>();

    if (timeStampedEntities != null)
    {
        foreach (var item in timeStampedEntities.Where(t => t.State == EntityState.Added))
                item.Entity.Created = DateTime.Now;
       }
    return base.SaveChanges();
}

這樣,您不必在每次創建要具有CreateTime屬性的實體時都設置值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM