从编辑视图返回的ASP.NET MVC 4模型属性值丢失

时间:2013-10-29 07:43:19

标签: asp.net-mvc model edit

我有一个没有脚手架的DateCreated值的模型。来到GET编辑控制器操作我看到模型具有传递给编辑视图的正确值。从视图回来,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>

}

1 个答案:

答案 0 :(得分:4)

在您的视图中,为DateCreated

放置一个隐藏元素
@Html.HiddenFor(m=>m.DateCreated)

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

相关问题