2012-02-06 52 views
0

我想硬編碼DateTime.Now(在前端)當一個新的記錄創建時。不過,我不想看到這些字段,因爲他們不需要輸入。使用下面,我拋出 「對象引用不設置到對象的實例。」綁定DateTime.Now使用MVC3剃刀

控制器上市代碼:

[HttpPost] 
public ActionResult Create(tbl_one tbl_one) 
{ 
    if (ModelState.IsValid) 
    { 
     db.tbl_one.Add(tbl_one); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    return View(tbl_one); 
} 

型號

public System.DateTime Created { get; set; } 

查看

<div class="editor-field"> 
    @Html.HiddenFor(model => model.Created, Model.Created = DateTime.Now) 
    @Html.ValidationMessageFor(model => model.Created) 
</div> 
+1

哪條線是扔? – JaredPar 2012-02-06 15:38:05

+0

@ Html.HiddenFor(model => model.Created,Model.Created = DateTime.Now) – 2012-02-06 16:28:30

回答

0

因爲型號對象尚未設置,您需要實例化它,當你返回創建一個GET請求觀點:

[HttpGet] 
public ActionResult Create(tbl_one tbl_one) 
{ 
    return View(new tbl_one()); 
} 
0

說實話,你可能不該」不要在前端做這件事。如果您在前端使用像DateTime.Now這樣的硬編碼值創建隱藏字段,那麼您仍然必須在後端檢查它以確保某人不會向您發送錯誤值作爲安全預防措施。我建議您只需將其設置在後端,以便您只需擔心一次。

2

部分信用到:MVC3 HTMLHelper defaults

修復:

@Html.HiddenFor(model => model.Created, new { @Value = System.DateTime.Now })