我有一个没有脚手架的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>


}

最佳答案

在您的视图中,将DateCreated的隐藏元素

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


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

10-04 17:40