Create Category

Rose Chang Dycd
3 min readMar 12, 2022

of ASP.NET Core (.Net 6) — 08

Now, we have to add a new Get action method in CategoryController.cs. Because we are not going to pass any data to the View, so the View() just left nothing in it.

Then add a new View according to the method. Set up the corresponding model as Category at the header.

Run and confirm that the button can enter the new view. Seems good.

Let’s add some labels and textboxes. We use asp-for tag helper so that can get the DB data, which in the Category.cs we’ve set up the column before.

Run and see it looks nice.

Then we add another DB column, DisplayOrder, and 2 buttons.

Now we add a new post-action method to push the change to the SQL database. We are going to retrieve an object to Category.

  1. If an action method is POST, we have to write the attribute [HttpPost].
  2. Then add [ValidateAntiForgeryToken] to avoid Cross-site request forgery attack (also known as XSRF or CSRF).
  3. Push new data into DB
  4. Save the DB change.
  5. Once the change saved, the changed will return to the View.

But rather then return view, we want to redirect to an action, to the Index action, inside the same controller. If you are going to redirect the action in some other controller, you can define the name at the following.

Run the application, enter test data, press Create, application pop-up no error, and check the DB, the new enter data does in to table now.

But once if we input blank in the column, we got error out there, so let’s make it smarter by adding some validation means.

In this case, we should add the validation inside the server side, which is the controller, as well as client side, which is inside the create view. And then you will find it validates greate!

Now, to make it more user-friendly, we add a pop-up reminder while invalidation hit.

--

--