2012-03-22 67 views
0

我在下面我申請一個學生類:與模型的選擇領域的工作在一個視圖中剃刀

public class Student 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string RoleNum { get; set; } 
    public DateTime RegistrationDate { get; set; } 
    public DateTime AdmissionDate { get; set; } 
} 

現在我的應用程序,更新學生模型的幾個觀點。但並非每個視圖都需要更新數據庫中學生表的每個字段。例如當學生首次創建時,註冊日期只設置一次。現在編輯學生視圖不應該再次更新RegistrationDate。

問題是RegistrationDate是數據庫中的必需字段,因此不包括視圖窗體中的該字段會生成RegistrationDate中具有NULL的異常。

因此,爲了防止這種情況,我將RegistrationDate字段隱藏在div中,因此它在表單中不可見。這是做這件事的正確方式,還是我錯過了一個非常簡單的方法?

回答

0

當更新實體的想法是首先從數據庫中讀取實體您要使用的ID進行更新,然後使用TryUpdateModel方法只更新了部分領域原始請求並最終保存模型。

下面是更新實體常用的模式:

[HttpPost] 
public ActionResult Update(int id) 
{ 
    Student student = Repository.GetStudent(id); 
    if (!TryUpdateModel(student)) 
    { 
     // there were validation errors => redisplay the view 
     return View(student); 
    } 

    // the model is valid => at this stage we could save it 
    Repository.Update(student); 
    return RedirectToAction("success"); 
} 
+0

但是,在被張貼的數據?在這裏,你只有ID張貼... – Romias 2012-03-22 21:35:24

+0

@Romias,數據是從您將在視圖中的HTML表單發佈。我只使用ID屬性作爲參數的事實並不意味着其他值不會存在。 'TryUpdateModel'使用請求中的所有值。所以你所要做的就是在表單中包含你感興趣的領域。 – 2012-03-22 21:36:48

+0

好吧,所以TryUpdateModel是一種更智能的活頁夾? – Romias 2012-03-22 21:38:39

0

而是藏匿其中的...只是讓他們隱藏字段:

@Html.HiddenFor(model => model.RegistrationDate) 

或者另一種選擇是隻使用一個隱藏的學生證,一旦你發佈數據到服務器(RegistrationDate會請爲空)...您可以從數據庫中獲取學生並填寫您爲空的值。

第二個選項更安全一些,因爲用戶不能在隱藏的客戶端上更改註冊日期。

check this question, very well explained.