0

使用 ASP.NET MVC4,我有一个 CreateView,用户在其中指定作者、文本和 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")
}
4

4 回答 4

2

通过 html 助手创建隐藏输入:

@Html.HiddenFor(model => model.CreateTime)
于 2013-09-21T01:07:34.493 回答
2

您可以设置编辑器的默认值

@Html.EditorFor( model => model.CreateTime, 
                                        new { @Value = DateTime.Now.ToShortDateString() })
于 2013-09-21T01:10:41.227 回答
1

如果您不希望用户设置任何内容,请不要将隐藏字段或其他任何地方放在 html 上。

在行动方法中发布后最好排除

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult  FormPostAction([Bind(Exclude = "CreateTime")] Topic topic)
{
and here you have to initialize CreateTime with whatever value you want...
}
于 2013-09-21T03:53:59.353 回答
1

首先定义一个接口

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 属性的任何实体时设置值。

于 2013-09-21T13:50:45.993 回答