Basic Learning Notes for ASP.NET Core MVC

Recently, due to the epidemic of "Wuhan pneumonia" at home, I have not been idle either. Recently, I have learned the basic knowledge of some web page development of core mvc, and I will go to the tutorial without saying more!


1. New Project


1) Create a new project - > Find " ASP.NET Core Web Application-type items (also obscure queries: language selection c#, project type selection Web):




2) Selection Web Application (Model View Controller) --->Modify Name--->Create:




3) When the new project is completed, the solution appears as shown in the diagram.





wwwroot stores front-end files such as js, css and so on.

Models-Model: Encapsulate business logic related data and how to process the data (checked in the Yellow box);

Views-View: Provides an interactive interface to the user (as checked in the blue box);

Controllers-Controller: responsible for controlling Model and View (checked in the red box as shown);

appsettings.json-Configuration file: If you can add a database connection string to it, as shown in the following figure:




2. Add Entity Model

1) Add an entity class (select Models--->Right-click--->Add--->Class--->Modify Name--->Create)

Add some features to the field as follows:


   /// <summary>
    /// User table
    /// </summary>
    public class InfoUser
        [Key]//Primary key has to ID Named primary key must be added
        [DisplayName("User name")]//Display Name
        [Required(ErrorMessage = "Hotel name cannot be empty")]//Property means the field cannot be empty
        public string UserName { get; set; }
        [Required(ErrorMessage = "Password cannot be empty")]
        public string Password { get; set; }
        [DisplayName("Creation date")]
        public DateTime DTCreate { get; set; }
        [DisplayName("Logon Date")]
        public DateTime DTLogin { get; set; } 
        public byte[] HeaderImg { get; set; }




2) Add another Entity Framework Class (Database Context Class)

And inherit DbContext

/// <summary>
/// Entity Framework EntityFrameworkCore
/// </summary>
namespace EasyBlog.Models
    public class DbWwp : DbContext
        public DbWwp(DbContextOptions<DbWwp> options)
         : base(options)

        public DbSet<InfoUser> InfoUsers { get; set; }
        public DbSet<InfoBlog> InfoBlogs { get; set; }
        public DbSet<InfoLog> InfoLogs { get; set; }
        public DbSet<InfoReply> InfoReplys { get; set; }



2) Adding packages is also required: Microsoft.EntityFrameworkCore.sqlserver and Microsoft.EntityFrameworkCore.Tools


Right-click Dependencies-->Manage NuGet Packages--->Browse--->Search Package Name--->Select the package you want to download and install






3) Register the database context in the ConfigureServices method in the Startup class


services.AddDbContext<DbWwp>(options => options.UseSqlServer(Configuration.GetConnectionString("DbWwp")));


4) Now let's open the Package Manager Console (Tools-->NuGet Package Manager-->Package Manager Console), write the command "add-migration init" as shown below, add a new database migration (init--the name of the migration).


Don't mind that the name after add-migration doesn't match the above image. Half the success will come from this yellow color.


Update-Database and return



5) There will be a "migration" in the context called the current creation date plus the name you created after the previous add, which is recorded and saved in the Magrations directory:




At this point, a basic MVC solution has been established, but it is basically empty

3. Add MVC and EF Framework


Introduction to concepts

Short form of MVC, Model-View-Controller


Model encapsulates business logic-related data and processes it


View provides user interface


Controller is responsible for controlling Model s and View s


1) Next we started to create a complete set of MVCs and add/delete checks, so we chose "View uses the MVC controller of the Entity Framework" (step: Controllers folder right-click --> Add --> Double-click Controller --> View uses the MVC controller of the Entity Framework):






2) Next, select the model class (such as InfoUsers created above), the data context class (such as the database context class created above) by dropping down, tick Generate View, click Add, and you can name it yourself, but the controller name must end with Controller (this is ASP.NET Core)A Convention for MVC, where we default to InfoUsersController


After the creation, the system automatically generated the controller (InfoUsers Controller below) and five views (Create-Add, Delete-Delete, Details-Check, Edit-Change, Index-Home page) automatically under the Views folder.


Of course, you can also create a View view yourself, but there are two ways to add a View view, one is directly under the Views folder (right-click the InfoUsers folder under the Views folder-->Add-->View)

The other is added through Action s in Controller.

Open the controller (such as InfoUsersController) and right-click --> Add View Method at "return View ();".But I recommend the latter approach.


3) After using the first two methods, you will enter the Add View Confirmation window as shown below, just add a point.




4) This adds another and a specific


The corresponding View(Login.cshtml) for troller and InfoUsers (here InfoUsersController and Login) is supplemented with the following code



    ViewData["Title"] = "Sign in";

<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Login">
            <div class="form-group">
                <label class="control-label">User name</label>
                <input name="UserName" id="UserName" class="form-control" />
            <div class="form-group">
                <label class="control-label">Password</label>
                <input name="Password" id="Password" type="password" class="form-control" />
            <div class="form-group">
                <input type="submit" value="Sign in" class="btn btn-primary" />



public IActionResult Login()
            return View();

        public async Task<ActionResult> Logining()
            var userName = Request.Form["UserName"];
            var password = Request.Form["Password"];
            var item = db.InfoUsers.Find(userName);

            if (item != null && password == item.Password)

                item.DTLogin = DateTime.Now;

                var claims = new List<Claim>();

                claims.Add(new Claim(ClaimTypes.Name, userName));

                var claimsIdentity = new ClaimsIdentity(claims, "Cookies");
                await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));
                return RedirectToAction("Index", "Blog");
                ViewBag.Msg = "Logon Failure";
            return View();



5) Run the program last (click IIS Express as shown in the diagramOr press F5, followed by/InfoUsers/Login (the address xx/InfoUsers/Login in the browser corresponds to the routing rule URL at the beginning: "{controller}/{action}/{id}") and press Enter after boot.


When you see the interface, it's successful.

Finally, please wear masks, wash your hands frequently and avoid going to crowds.Protect yourself from adding trouble to your motherland!!!Go to Wuhan!Go China!!!

Tags: ASP.NET Database JSON IIS

Posted on Tue, 18 Feb 2020 11:34:06 -0500 by jhuaraya