建立 - 控制器部分

要實現建立功能,我們需要兩個操作: GETPOST

  1. 用於返回檢視的 GET 操作將顯示允許使用者使用 HTML 元素輸入資料的表單。如果在使用者新增任何資料之前要插入一些預設值,則應將其分配給此操作的檢視模型屬性。

  2. 當使用者填寫表單並單擊儲存按鈕時,我們將處理表單中的資料。因此,我們現在需要 POST 操作。此方法將負責管理資料並將其儲存到資料庫。如果出現任何錯誤,則返回的相同檢視會顯示儲存的表單資料和錯誤訊息,說明提交操作後出現的問題。

我們將在控制器類中的兩個 Create() 方法中實現這兩個步驟。

    // GET: Student/Create 
    // When the user access this the link ~/Student/Create a get request is made to controller Student and action Create, as the page just need to build a blank form, any information is needed to be passed to view builder
    public ActionResult Create()
    {
        // Creates a ViewResult object that renders a view to the response.
        // no parameters means: view = default in this case Create and model = null
        return View();
    }

    // POST: Student/Create        
    [HttpPost]
    // Used to protect from overposting attacks, see http://stackoverflow.com/documentation/asp.net-mvc/1997/html-antiforgerytoke for details
    [ValidateAntiForgeryToken]
    // This is the post request with forms data that will be bind the action, if in the data post request have enough information to build a Student instance that will be bind
    public ActionResult Create(Student student)
    {
        try
        {
        //Gets a value that indicates whether this instance received from the view is valid.
            if (ModelState.IsValid)
            {
                // Adds to the context
                db.Students.Add(student);
                // Persist the data 
                db.SaveChanges();
                // Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action, in this case the index action.
                return RedirectToAction("Index");
            }
        }
        catch 
        {
            // Log the error (uncomment dex variable name and add a line here to write a log).
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        // view = default in this case Create and model = student
        return View(student);
    }