4

我有一个没有脚手架的 DateCreated 值的模型。来到 GET Edit 控制器操作,我看到模型具有传递到 Edit 视图的正确值。从视图回来,POST 方法,DateCreated 的值是 DateTime 默认值。它丢失了。有谁知道为什么?控制器和视图是脚手架的。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Product product)
    {
        try
        {
            if (ModelState.IsValid)
            {
                product.DateEdited = DateTime.Now;
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DataException dex)
        {
            Console.Write(dex.Message);
            ModelState.AddModelError("", reg6.Resources.UnableToSaveChanges);
        }
        return View(product);
    }

@model reg6.Models.Product

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

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

<fieldset>
    <legend>Product</legend>
    <table>
    <tr>
        <td>
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
        </td>
        <td>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name)
                <div>
                    @Html.ValidationMessageFor(model => model.Name)
                </div>
            </div>
        </td>
    <tr>
    <tr>
        <td>
            <div class="editor-label">
                @Html.LabelFor(model => model.Description)
            </div>
        </td>
        <td>
            <div class="editor-field">
                @Html.EditorFor(model => model.Description)
                <div>
                    @Html.ValidationMessageFor(model => model.Description)
                </div>
            </div>
        </td>
    <tr>
    <tr>
        <td>
            <div class="editor-label">
                @Html.LabelFor(model => model.BasePrice)
            </div>
        </td>
        <td>
            <div class="editor-field">
                @Html.EditorFor(model => model.BasePrice)
                <div>
                    @Html.ValidationMessageFor(model => model.BasePrice)
                </div>
            </div>
        </td>
    <tr>


    <tr>
    <td>
        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
    </td>
    <td align="right">
        <input type="submit" value="Create" id='CreateButton' />
    <td>
    </tr>
    </table>

</fieldset>

}

4

1 回答 1

6

在您的视图中放置一个隐藏元素DateCreated

@Html.HiddenFor(m=>m.DateCreated)

所有隐藏的元素都将发布到服务器。

于 2013-10-29T08:13:29.760 回答