创建 - 控制器部分

要实现创建功能,我们需要两个操作: 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);
    }