2017-01-17 54 views
-1

我有一個屬性Last_edited在我的模型中想要設置代碼端。我也有像Name這應該由用戶設置的屬性。我使用Code First,這個Edit方法是由Entity Framework生成的。我還沒有找到如何做到這一點。MVC設置特定屬性代碼端

這裏是我的控制器編輯方法:

public ActionResult Edit(int? id) 
{ 
    if (id == null) 
    { 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 
     Product product = db.Product.Find(id); 
     if (product == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(product); 
} 
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit([Bind(Include = "Id,Name,Comment,Last_edited")] Product product) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Entry(product).State = EntityState.Modified; 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
    } 
     return View(product); 
} 
+0

或者只是讓它像這樣,並設置Last_edited也serverside。作爲ovverride – lordkain

+0

如果你只需要在代碼中使用Last_edited,並且你不想在你的視圖中顯示它,只需從你的「include」語句中刪除ir即可。 –

回答

2

Bind屬性包含列表中刪除Last_edited,並自行設定值的操作方法。

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit([Bind(Include = "Id,Name,Comment")] Product product) 
{ 
    product.Last_Edited = DateTime.UtcNow; 
    if (ModelState.IsValid) 
    {   
     db.Entry(product).State = EntityState.Modified; 
     db.SaveChanges(); 

     return RedirectToAction("Index"); 
    } 
    return View(product); 
} 

假設Last_editedDateTime類型。如果它是不同的類型,請設置適當的值。

由於我們在action方法中設置了此屬性的值,所以不需要在窗體中保留此屬性的輸入字段。

作爲便箋,The best way to prevent overposting is by using a (view specific) view model class。這也可以讓你創建鬆散耦合的程序。

+0

是不是更好的是隻使用需要通過視圖傳遞的propeties使用viewmodel? –

+0

是的。最好和鬆散耦合的方式來防止重疊是通過使用視圖模型(http://stackoverflow.com/questions/34260334/mvc-6-bind-attribute-disappears/34260397#34260397)。 OP是MVC的新手,正在使用IDE生成的代碼。我不想混淆他。我會更新答案,包括鏈接 – Shyju

+0

是的,這將是很好的補充,更好的方法是爲未來的讀者。 –

相關問題