Module goal: In this module we are teaching the audience how to build a simple CRUD application and intro to PRG. During the module will be introduced to the following:
- Learn how to create a Form with ASP.NET Core
- Overview of the to ASP.NET Core Web Application template
- Introduction to Web API
-
Open up Visual Studio
-
Create a new ASP.NET Core application
Go to File New Project ->.NETCore -> ASP.NET Core Web Application (.NET Core)
-
Enter the name MusicStore
-
Click Change authentication and Select Individual User Accounts
This can also be done in the commandline with
```
dotnet new mvc
```
Make a list of Music albums
- Right click on the Model folder --> Add --> Class --> albums
public class albums
{
public int ID { get; set; }
public String Artist { get; set; }
public String Album { get; set; }
public String Genre { get; set; }
public DateTime ReleaseDate { get; set; }
public decimal Price { get; set; }
}
- Right click on the Controller folder --> Add --> scaffolded items
- Select the MVC Controller with Views, using Entity Framework
- Select your Model Class : albums(MusicStore.Models)
- Select Data Context class: ApplicationDbContext(MusicStore.Data)
- Now, you should that this has scaffolded a new AlbumsControllers and 5 new Views
Albums Controller
Albums Views
- Run the application and navigate to /albums
Should see the errror below
Add Database
Option 1: Use Visual Studio
In Visual Studio, use the Package Manager Console to scaffold a new migration for these changes and apply them to the database:
PM> Add-Migration [migration name]
PM> Update-Database
Option 2: Use dotnet CLI
dotnet ef migrations add [migration name]
dotnet ef database update
- Run your application again and go to /albums
- Click Create new
Quick note: This was an HTTP GET
- Add an entry an album and hit create
Quick note: By simply creating a new item you have performed a Post Redirect Get (PRG).
- Open your albums Model (albums.cs)
namespace MusicStore.Models
{
public class albums
{
public int ID { get; set; }
public String Artist { get; set; }
public String Album { get; set; }
public String Genre { get; set; }
public DateTime ReleaseDate { get; set; }
public decimal Price { get; set; }
}
}
-
Let's add the following validation to the form (Learn more here)
- Album title needs to be at least 3 characters
- And the Genre shouldn't have crazy characters
- Albums Price should be under $20
-
Add
using System.ComponentModel.DataAnnotations;
namespace MusicStore.Models
{
public class albums
{
public int ID { get; set; }
[Required]
public String Artist { get; set; }
[StringLength(60, MinimumLength =3)]
[Required]
public String Album { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
public String Genre { get; set; }
[Required]
public DateTime ReleaseDate { get; set; }
[Required]
[Range(0, 20.00)]
public decimal Price { get; set; }
}
}
- Run the application and navigate to albums/Create
Test validation by entering 1 for Album and $ for Genre