asp.net-mvc CRUD operation Create - Controller Part

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

To implement the create functionality we need two actions: GET and POST.

  1. The GET action used to return view which will show a form allowing user to input data using HTML elements. If there are some default values to be inserted before user adding any data, it should be assigned to the view model properties on this action.

  2. When the user fills the form and clicks the "Save" button we will be dealing with data from the form. Because of that now we need the POST action. This method will be responsible for managing data and saving it to database. In case of any errors, the same view returned with stored form data & error message explains what problem occurs after submit action.

We'll implement these two steps within two Create() methods within our controller class.

    // 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);
    }


Got any asp.net-mvc Question?