2013-10-29 36 views
2

我有一個模型的DateCreated值不是腳手架。即將到來編輯控制器操作我看到該模型具有傳遞到編輯視圖的正確值。從視圖POST方法回來,DateCreated的值是DateTime默認值。它丟失了。 有誰知道爲什麼?控制器和視圖是腳手架的。ASP.NET MVC 4模型屬性值丟失從編輯視圖返回

[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

請粘貼一些代碼 –

回答

4

您認爲地方隱藏的元素爲DateCreated

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

所有隱藏要素將被髮送到服務器。

+0

如何在html頁面中檢查隱藏的字段值是否存在? – elector

+0

ID字段也是隱藏的,我沒有在視圖標記中看到它,並且不知道在頁面本身中尋找什麼... – elector

+0

@elector:模型綁定到元素名稱。不是元素ID。檢查從HiddenFor幫助器生成的代碼,你會理解它。它會產生像這樣的東西。「'。即使你可以像這樣在表單中包含隱藏的輸入字段。 '' – Haritha