Chuyển tới nội dung
Home » Visual Studio 2019 Mvc | Cấu Trúc Solution Explorer

Visual Studio 2019 Mvc | Cấu Trúc Solution Explorer

Visual Studio 2019 Installation and Creation of MVC project

Set up EF 6 to use LocalDB

LocalDB is a lightweight version of the SQL Server Express database engine. It’s easy to install and configure, starts on demand, and runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to work with databases as .mdf files. You can put LocalDB database files in the App_Data folder of a web project if you want to be able to copy the database with the project. The user instance feature in SQL Server Express also enables you to work with .mdf files, but the user instance feature is deprecated; therefore, LocalDB is recommended for working with .mdf files. LocalDB is installed by default with Visual Studio.

Typically, SQL Server Express is not used for production web applications. LocalDB in particular is not recommended for production use with a web application because it’s not designed to work with IIS.

  • In this tutorial, you’ll work with LocalDB. Open the application Web.config file and add a


    connectionStrings

    element preceding the

    appSettings

    element, as shown in the following example. (Make sure you update the Web.config file in the root project folder. There’s also a Web.config file in the Views subfolder that you don’t need to update.)

The connection string you’ve added specifies that Entity Framework will use a LocalDB database named ContosoUniversity1.mdf. (The database doesn’t exist yet but EF will create it.) If you want to create the database in your App_Data folder, you could add

AttachDBFilename=|DataDirectory|\ContosoUniversity1.mdf

to the connection string. For more information about connection strings, see SQL Server Connection Strings for ASP.NET Web Applications.

You don’t actually need a connection string in the Web.config file. If you don’t supply a connection string, Entity Framework uses a default connection string based on your context class. For more information, see Code First to a New Database.

Tải xuống

Tài liệu

Nhằm phục vụ mục đích học tập Offline của cộng đồng, Kteam hỗ trợ tính năng lưu trữ nội dung bài học Tạo 1 project ASP.Net MVC đơn giản và giải thích cấu trúc, vai trò của View, Controller trong mô hình MVC. dưới dạng file PDF trong link bên dưới.

Ngoài ra, bạn cũng có thể tìm thấy các tài liệu được đóng góp từ cộng đồng ở mục TÀI LIỆU trên thư viện Howkteam.com

Đừng quên like và share để ủng hộ Kteam và tác giả nhé!

Visual Studio 2019 Installation and Creation of MVC project
Visual Studio 2019 Installation and Creation of MVC project

Thảo luận

Nếu bạn có bất kỳ khó khăn hay thắc mắc gì về khóa học, đừng ngần ngại đặt câu hỏi trong phần bên dưới hoặc trong mục HỎI & ĐÁP trên thư viện Howkteam.com để nhận được sự hỗ trợ từ cộng đồng.

Nội dung bài viết

Khóa học

Lập trình website với ASP.Net MVC cơ bản

Lập trình website với ASP.Net MVC cơ bản

Đánh giá

Bình luận

Dạ cho em hỏi ạ. Luyện tập thử thách không ngại khó là làm gì ạ?

Thanks Hkteam đã chia sẽ kiến thức mong hkteam ra thêm nhiều clip hay và thực tế

Getting started with ASP.NET MVC 5

Note

An updated version of this tutorial is available here using the latest version of Visual Studio. The new tutorial uses ASP.NET Core MVC, which provides many improvements over this tutorial.

This tutorial teaches ASP.NET Core MVC with controllers and views. Razor Pages is a new alternative in ASP.NET Core, a page-based programming model that makes building web UI easier and more productive. We recommend you try the Razor Pages tutorial before the MVC version. The Razor Pages tutorial:

  • Is easier to follow.
  • Covers more features.
  • Is the preferred approach for new app development.

This tutorial teaches you the basics of building an ASP.NET MVC 5 web app using Visual Studio 2017. The final source code for the tutorial is located on GitHub.

This tutorial was written by Scott Guthrie (twitter@scottgu ), Scott Hanselman (twitter: @shanselman ), and Rick Anderson ( @RickAndMSFT )

You need an Azure account to deploy this app to Azure:

  • You can open an Azure account for free – You get credits you can use to try out paid Azure services, and even after they’re used up you can keep the account and use free Azure services.
  • You can activate MSDN subscriber benefits – Your MSDN subscription gives you credits every month that you can use for paid Azure services.

2.MVC

Ở đây, chúng ta vừa tạo ra một ASP.NET MVC project nên sẽ có thêm 3 folder Controllers, Models và Views. Controllers: Chứa các controller. Models: Chứa các file tương tác với CSDL. Views: Thư mục chứa các file HTML với đuôi là .cshtml.

Các file HTML trong ASP.NET MVC

Các file này còn được gọi là Razor file. Controller trong MVC gọi View bằng cách gán dữ liệu để tạo giao diện. View phải có khả năng xử lý dữ liệu và tạo response. Điều này được xử lý bằng cách dùng Razor, nó cho chúng ta sử dụng C# code trong file HTML.Các file chứa Razor có đuôi .cshtml. Cú pháp Razor thường ngắn hơn và đơn giản hơn cũng dễ học như C#. Sau này, mình sẽ có 1 bài viết cũ thể hơn về Razor View Engine.

Như vậy, mình đã giới thiệu sơ qua về cách tạo một project ASP.NET bằng Visual Studio 2019. Ở bài viết tới, mình sẽ ứng dụng mô hình MVC để tạo một trang web đơn giản.

Từ năm 2016 ASP.NET đã trở thành một phần mềm mã nguồn mở và có thể xây dựng web app và hosting trên mọi nên tảng khác như Ubuntu, Max OS với VScode chứ không chỉ Windows. Các bạn có thể tham khảo cách cài đặt ASP.NET core trên các nền tảng khác như Ubuntu, MacOS tại đây.

All rights reserved

Tutorial: Get Started with Entity Framework 6 Code First using MVC 5

Note

For new development, we recommend ASP.NET Core Razor Pages over ASP.NET MVC controllers and views. For a tutorial series similar to this one using Razor Pages, see Tutorial: Get started with Razor Pages in ASP.NET Core. The new tutorial:

  • Is easier to follow.
  • Provides more EF Core best practices.
  • Uses more efficient queries.
  • Is more current with the latest API.
  • Covers more features.
  • Is the preferred approach for new application development.

In this series of tutorials, you learn how to build an ASP.NET MVC 5 application that uses Entity Framework 6 for data access. This tutorial uses the Code First workflow. For information about how to choose between Code First, Database First, and Model First, see Create a model.

This tutorial series explains how to build the Contoso University sample application. The sample application is a simple university website. With it, you can view and update student, course, and instructor information. Here are two of the screens you create:

In this tutorial, you:

  • Create an MVC web app
  • Set up the site style
  • Install Entity Framework 6
  • Create the data model
  • Create the database context
  • Initialize DB with test data
  • Set up EF 6 to use LocalDB
  • Create controller and views
  • View the database
MVC web application-Part 1 Visual Studio 2019 | Step-by-step ASP.NET MVC Tutorial for Beginners
MVC web application-Part 1 Visual Studio 2019 | Step-by-step ASP.NET MVC Tutorial for Beginners

Conventions

The amount of code you had to write in order for Entity Framework to be able to create a complete database for you is minimal because of conventions, or assumptions that Entity Framework makes. Some of them have already been noted or were used without your being aware of them:

  • The pluralized forms of entity class names are used as table names.
  • Entity property names are used for column names.
  • Entity properties that are named

    ID

    or classname

    ID

    are recognized as primary key properties.
  • A property is interpreted as a foreign key property if it’s named
    (for example,

    StudentID

    for the

    Student

    navigation property since the

    Student

    entity’s primary key is

    ID

    ). Foreign key properties can also be named the same simply (for example,

    EnrollmentID

    since the

    Enrollment

    entity’s primary key is

    EnrollmentID

    ).

You’ve seen that conventions can be overridden. For example, you specified that table names shouldn’t be pluralized, and you’ll see later how to explicitly mark a property as a foreign key property.

Create an MVC web app

  1. Open Visual Studio and create a C# web project using the ASP.NET Web Application (.NET Framework) template. Name the project ContosoUniversity and select OK.

  2. In New ASP.NET Web Application – ContosoUniversity, select MVC.

    Note

    By default, the Authentication option is set to No Authentication. For this tutorial, the web app doesn’t require users to sign in. Also, it doesn’t restrict access based on who’s signed in.

  3. Select OK to create the project.

Tạo ứng dụng MVC đầu tiên trong visual studio 2019
Tạo ứng dụng MVC đầu tiên trong visual studio 2019

This tutorial teaches ASP.NET Core MVC web development with controllers and views. If you’re new to ASP.NET Core web development, consider the Razor Pages version of this tutorial, which provides an easier starting point. See Choose an ASP.NET Core UI, which compares Razor Pages, MVC, and Blazor for UI development.

This is the first tutorial of a series that teaches ASP.NET Core MVC web development with controllers and views.

At the end of the series, you’ll have an app that manages and displays movie data. You learn how to:

The Visual Studio Code instructions use the .NET CLI for ASP.NET Core development functions such as project creation. You can follow these instructions on macOS, Linux, or Windows and with any code editor. Minor changes may be required if you use something other than Visual Studio Code.

Change to the directory (cd) that will contain the project.

Run the following commands:

dotnet new mvc -o MvcMovie
code -r MvcMovie

The dotnet new command creates a new ASP.NET Core MVC project in the MvcMovie folder.

The code command opens the MvcMovie project folder in the current instance of Visual Studio Code.

Visual Studio Code might display a dialog box that asks: Do you trust the authors of the files in this folder?

If you trust all files in the parent folder, select Trust the authors of all files in the parent folder.

Select Yes, I trust the authors since the project folder has files generated by .NET.

When Visual Studio Code requests that you add assets to build and debug the project, select Yes. If Visual Studio Code doesn’t offer to add build and debug assets, select View > Command Palette and type “.NET” into the search box. From the list of commands, select the .NET: Generate Assets for Build and Debug command.

Visual Studio Code adds a .vscode folder with generated launch.json and tasks.json files.

Select File > New Project….

Select Web and Console > App > Web Application (Model-View-Controller) > Continue.

In the Configure your new Web Application (Model-View-Controller) dialog:

Select .NET 8.0 for the Target Framework.

Verify that Do not use top-level statements is unchecked.

Select Continue.

Enter MvcMovie for Project name. It’s important to name the project MvcMovie. Capitalization needs to match each namespace when code is copied.

Visual Studio runs the app and opens the default browser.

The address bar shows localhost: and not something like example.com. The standard hostname for your local computer is localhost. When Visual Studio creates a web project, a random port is used for the web server.

Launching the app without debugging by selecting Ctrl+F5 allows you to:

Make code changes.

Save the file.

Quickly refresh the browser and see the code changes.

You can launch the app in debug or non-debug mode from the Debug menu:

You can debug the app by selecting the https button in the toolbar:

The following image shows the app:

Select F5 to run the app.

Trust the HTTPS development certificate by running the following command:

dotnet dev-certs https –trust

The preceding command doesn’t work on Linux. See your Linux distribution’s documentation for trusting a certificate.

The preceding command displays the following dialog, provided the certificate was not previously trusted:

Select Yes if you agree to trust the development certificate.

This tutorial teaches ASP.NET Core MVC web development with controllers and views. If you’re new to ASP.NET Core web development, consider the Razor Pages version of this tutorial, which provides an easier starting point. See Choose an ASP.NET Core UI, which compares Razor Pages, MVC, and Blazor for UI development.

This is the first tutorial of a series that teaches ASP.NET Core MVC web development with controllers and views.

At the end of the series, you’ll have an app that manages and displays movie data. You learn how to:

The Visual Studio Code instructions use the .NET CLI for ASP.NET Core development functions such as project creation. You can follow these instructions on macOS, Linux, or Windows and with any code editor. Minor changes may be required if you use something other than Visual Studio Code.

Change to the directory (cd) that will contain the project.

Run the following commands:

dotnet new mvc -o MvcMovie
code -r MvcMovie

The dotnet new command creates a new ASP.NET Core MVC project in the MvcMovie folder.

The code command opens the MvcMovie project folder in the current instance of Visual Studio Code.

Visual Studio Code might display a dialog box that asks: Do you trust the authors of the files in this folder?

If you trust all files in the parent folder, select Trust the authors of all files in the parent folder.

Select Yes, I trust the authors since the project folder has files generated by .NET.

When Visual Studio Code requests that you add assets to build and debug the project, select Yes. If Visual Studio Code doesn’t offer to add build and debug assets, select View > Command Palette and type “.NET” into the search box. From the list of commands, select the .NET: Generate Assets for Build and Debug command.

Visual Studio Code adds a .vscode folder with generated launch.json and tasks.json files.

Start Visual Studio for Mac and select File > New Project….

In Visual Studio for Mac select Web and Console > App > Web Application (Model-View-Controller) > Continue.

In the Configure your new Web Application (Model-View-Controller) dialog:

Select .NET 7.0 for the Target Framework.

Verify that Do not use top-level statements is unchecked.

Select Continue.

Enter MvcMovie for Project name. It’s important to name the project MvcMovie. Capitalization needs to match each namespace when code is copied.

Visual Studio runs the app and opens the default browser.

The address bar shows localhost: and not something like example.com. The standard hostname for your local computer is localhost. When Visual Studio creates a web project, a random port is used for the web server.

Launching the app without debugging by selecting Ctrl+F5 allows you to:

Make code changes.

Save the file.

Quickly refresh the browser and see the code changes.

You can launch the app in debug or non-debug mode from the Debug menu:

You can debug the app by selecting the https button in the toolbar:

The following image shows the app:

Select F5 to run the app.

Trust the HTTPS development certificate by running the following command:

dotnet dev-certs https –trust

The preceding command doesn’t work on Linux. See your Linux distribution’s documentation for trusting a certificate.

The preceding command displays the following dialog, provided the certificate was not previously trusted:

Select Yes if you agree to trust the development certificate.

This tutorial teaches ASP.NET Core MVC web development with controllers and views. If you’re new to ASP.NET Core web development, consider the Razor Pages version of this tutorial, which provides an easier starting point. See Choose an ASP.NET Core UI, which compares Razor Pages, MVC, and Blazor for UI development.

This is the first tutorial of a series that teaches ASP.NET Core MVC web development with controllers and views.

At the end of the series, you’ll have an app that manages and displays movie data. You learn how to:

The Visual Studio Code instructions use the .NET CLI for ASP.NET Core development functions such as project creation. You can follow these instructions on macOS, Linux, or Windows and with any code editor. Minor changes may be required if you use something other than Visual Studio Code.

For Visual Studio for Mac, see the .NET 7 version of this tutorial.

Change to the directory (cd) that will contain the project.

Run the following commands:

dotnet new mvc -o MvcMovie
code -r MvcMovie

The dotnet new command creates a new ASP.NET Core MVC project in the MvcMovie folder.

The code command opens the MvcMovie project folder in the current instance of Visual Studio Code.

Visual Studio Code might display a dialog box that asks: Do you trust the authors of the files in this folder?

If you trust all files in the parent folder, select Trust the authors of all files in the parent folder.

Select Yes, I trust the authors since the project folder has files generated by .NET.

When Visual Studio Code requests that you add assets to build and debug the project, select Yes. If Visual Studio Code doesn’t offer to add build and debug assets, select View > Command Palette and type “.NET” into the search box. From the list of commands, select the .NET: Generate Assets for Build and Debug command.

Visual Studio Code adds a .vscode folder with generated launch.json and tasks.json files.

For Visual Studio for Mac, see the .NET 7 version of this tutorial.

Visual Studio runs the app and opens the default browser.

The address bar shows localhost: and not something like example.com. The standard hostname for your local computer is localhost. When Visual Studio creates a web project, a random port is used for the web server.

Launching the app without debugging by selecting Ctrl+F5 allows you to:

Make code changes.

Save the file.

Quickly refresh the browser and see the code changes.

You can launch the app in debug or non-debug mode from the Debug menu:

You can debug the app by selecting the MvcMovie button in the toolbar:

The following image shows the app:

Select Ctrl+F5 to run without the debugger.

Trust the HTTPS development certificate by running the following command:

dotnet dev-certs https –trust

The preceding command doesn’t work on Linux. See your Linux distribution’s documentation for trusting a certificate.

The preceding command displays the following dialog, provided the certificate was not previously trusted:

Select Yes if you agree to trust the development certificate.

This tutorial teaches ASP.NET Core MVC web development with controllers and views. If you’re new to ASP.NET Core web development, consider the Razor Pages version of this tutorial, which provides an easier starting point. See Choose an ASP.NET Core UI, which compares Razor Pages, MVC, and Blazor for UI development.

This is the first tutorial of a series that teaches ASP.NET Core MVC web development with controllers and views.

At the end of the series, you’ll have an app that manages and displays movie data. You learn how to:

The Visual Studio Code instructions use the .NET CLI for ASP.NET Core development functions such as project creation. You can follow these instructions on macOS, Linux, or Windows and with any code editor. Minor changes may be required if you use something other than Visual Studio Code.

Change to the directory (cd) that will contain the project.

Run the following commands:

dotnet new mvc -o MvcMovie
code -r MvcMovie

The dotnet new command creates a new ASP.NET Core MVC project in the MvcMovie folder.

The code command opens the MvcMovie project folder in the current instance of Visual Studio Code.

Visual Studio Code might display a dialog box that asks: Do you trust the authors of the files in this folder?

If you trust all files in the parent folder, select Trust the authors of all files in the parent folder.

Select Yes, I trust the authors since the project folder has files generated by .NET.

When Visual Studio Code requests that you add assets to build and debug the project, select Yes. If Visual Studio Code doesn’t offer to add build and debug assets, select View > Command Palette and type “.NET” into the search box. From the list of commands, select the .NET: Generate Assets for Build and Debug command.

Visual Studio Code adds a .vscode folder with generated launch.json and tasks.json files.

Select File > New Solution.

In Visual Studio for Mac earlier than version 8.6, select .NET Core > App > Web Application (Model-View-Controller) > Next. In version 8.6 or later, select Web and Console > App > Web Application (Model-View-Controller) > Next.

In the Configure your new Web Application dialog:

Confirm that Authentication is set to No Authentication.

If an option to select a Target Framework is presented, select the latest 5.x version.

Select Next.

Name the project MvcMovie, and then select Create.

The address bar shows localhost:port# and not something like example.com. The standard hostname for your local computer is localhost. When Visual Studio creates a web project, a random port is used for the web server.

Launching the app without debugging by selecting Ctrl+F5 allows you to:

Make code changes.

Save the file.

Quickly refresh the browser and see the code changes.

You can launch the app in debug or non-debug mode from the Debug menu item:

You can debug the app by selecting the IIS Express button

The following image shows the app:

Select Ctrl+F5 to run without the debugger.

Trust the HTTPS development certificate by running the following command:

dotnet dev-certs https –trust

The preceding command doesn’t work on Linux. See your Linux distribution’s documentation for trusting a certificate.

The preceding command displays the following dialog, provided the certificate was not previously trusted:

Select Yes if you agree to trust the development certificate.

The address bar shows localhost:port# and not something like example.com. The standard hostname for your local computer is localhost. When Visual Studio creates a web project, a random port is used for the web server.

You can launch the app in debug or non-debug mode from the Run menu.

This tutorial teaches ASP.NET Core MVC web development with controllers and views. If you’re new to ASP.NET Core web development, consider the Razor Pages version of this tutorial, which provides an easier starting point. See Choose an ASP.NET Core UI, which compares Razor Pages, MVC, and Blazor for UI development.

This is the first tutorial of a series that teaches ASP.NET Core MVC web development with controllers and views.

At the end of the series, you’ll have an app that manages and displays movie data. You learn how to:

The Visual Studio Code instructions use the .NET Core CLI for ASP.NET Core development functions such as project creation. You can follow these instructions on any platform (macOS, Linux, or Windows) and with any code editor. Minor changes may be required if you use something other than Visual Studio Code. For more information on installing Visual Studio Code on macOS, see Visual Studio Code on macOS.

Change directories (cd) to a folder that will contain the project.

Run the following command:

dotnet new mvc -o MvcMovie
code -r MvcMovie

A dialog box appears with Required assets to build and debug are missing from ‘MvcMovie’. Add them?, select Yes.

dotnet new mvc -o MvcMovie: Creates a new ASP.NET Core MVC project in the MvcMovie folder.

code -r MvcMovie: Loads the MvcMovie.csproj project file in Visual Studio Code.

Select File > New Solution.

In Visual Studio for Mac earlier than version 8.6, select .NET Core > App > Web Application (Model-View-Controller) > Next. In version 8.6 or later, select Web and Console > App > Web Application (Model-View-Controller) > Next.

In the Configure your new Web Application dialog:

Confirm that Authentication is set to No Authentication.

If an option to select a Target Framework is presented, select the latest 3.x version.

Select Next.

Name the project MvcMovie, and then select Create.

The address bar shows localhost:port# and not something like example.com. The standard hostname for your local computer is localhost. When Visual Studio creates a web project, a random port is used for the web server.

Launching the app without debugging by selecting Ctrl+F5 allows you to:

Make code changes.

Save the file.

Quickly refresh the browser and see the code changes.

You can launch the app in debug or non-debug mode from the Debug menu item:

You can debug the app by selecting the IIS Express button

The following image shows the app:

Select Ctrl+F5 to run the app without debugging.

Trust the HTTPS development certificate by running the following command:

dotnet dev-certs https –trust

The preceding command doesn’t work on Linux. See your Linux distribution’s documentation for trusting a certificate.

The preceding command displays the following dialog, provided the certificate was not previously trusted:

Select Yes if you agree to trust the development certificate.

The address bar shows localhost:port# and not something like example.com. The standard hostname for your local computer is localhost. When Visual Studio creates a web project, a random port is used for the web server. When you run the app, you’ll see a different port number.

You can launch the app in debug or non-debug mode from the Run menu.

Xây dựng một ví dụ đơn giản với ASP.NET MVC 5. Ta cũng biết ASP.NET là một ngôn ngữ rất được nhiều lập trình viên dùng hiện này, bởi vì nó bảo mật rất tuyệt vờiNay mình chia sẻ cách xây dựng ASP.NET MVC 5 trên phần mềm Visual Studio 2019Đầu tiên các bạn cần tải Visual Studio 2019 về máy tính, bạn bấm vào đây https://docs.microsoft.com/en-gb/visualstudio/releases/2019/release-notesSau khi tải về bạn cứ cái đặt bình thường, chọn các plugin cần dùng và bạn chuyển qua Individual Components, sao đó nhớ chọn Class Designer và LINQ to SQL Tools nhé

Install Entity Framework 6

  1. From the Tools menu, choose NuGet Package Manager, and then choose Package Manager Console.

  2. In the Package Manager Console window, enter the following command:


    Install-Package EntityFramework

This step is one of a few steps that this tutorial has you do manually, but that could have been done automatically by the ASP.NET MVC scaffolding feature. You’re doing them manually so that you can see the steps required to use Entity Framework (EF). You’ll use scaffolding later to create the MVC controller and views. An alternative is to let scaffolding automatically install the EF NuGet package, create the database context class, and create the connection string. When you’re ready to do it that way, all you have to do is skip those steps and scaffold your MVC controller after you create your entity classes.

Kết luận

Qua bài học ngày hôm nay, các bạn đã hiểu về View, Controller cũng như cách tạo 1 project ASP.Net MVC và tạo 1 ví dụ đơn giản là xuất câu “Hello Howkteam” ra màn hình rồi nhé.

Bài sau chúng ta sẽ đi vào Tìm hiểu về Layout Page trong View và tạo ví dụ minh họa

Cảm ơn các bạn đã theo dõi bài viết. Hãy để lại bình luận hoặc góp ý của mình để phát triển bài viết tốt hơn. Đừng quên “Luyện tập – Thử thách – Không ngại khó”.

Part 1 - Create Asp.Net MVC Project in Visual Studio 2019 Step by Step
Part 1 – Create Asp.Net MVC Project in Visual Studio 2019 Step by Step

Create controller and views

Now you’ll create a web page to display data. The process of requesting the data automatically triggers the creation of the database. You’ll begin by creating a new controller. But before you do that, build the project to make the model and context classes available to MVC controller scaffolding.

  1. Right-click the Controllers folder in Solution Explorer, select Add, and then click New Scaffolded Item.

  2. In the Add Scaffold dialog box, select MVC 5 Controller with views, using Entity Framework, and then choose Add.

  3. In the Add Controller dialog box, make the following selections, and then choose Add:

    • Model class: Student (ContosoUniversity.Models). (If you don’t see this option in the drop-down list, build the project and try again.)

    • Data context class: SchoolContext (ContosoUniversity.DAL).

    • Controller name: StudentController (not StudentsController).

    • Leave the default values for the other fields.

      When you click Add, the scaffolder creates a StudentController.cs file and a set of views (.cshtml files) that work with the controller. In the future when you create projects that use Entity Framework, you can also take advantage of some additional functionality of the scaffolder: create your first model class, don’t create a connection string, and then in the Add Controller box specify New data context by selecting the + button next to Data context class. The scaffolder will create your


      DbContext

      class and your connection string as well as the controller and views.

  4. Visual Studio opens the Controllers\StudentController.cs file. You see that a class variable has been created that instantiates a database context object:


    private SchoolContext db = new SchoolContext();

    The


    Index

    action method gets a list of students from the Students entity set by reading the

    Students

    property of the database context instance:

    public ViewResult Index() { return View(db.Students.ToList()); }

    The Student\Index.cshtml view displays this list in a table:

    @foreach (var item in Model) {

    }

    @Html.DisplayNameFor(model => model.LastName) @Html.DisplayNameFor(model => model.FirstMidName) @Html.DisplayNameFor(model => model.EnrollmentDate)
    @Html.DisplayFor(modelItem => item.LastName) @Html.DisplayFor(modelItem => item.FirstMidName) @Html.DisplayFor(modelItem => item.EnrollmentDate) @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Html.ActionLink("Delete", "Delete", new { id=item.ID })

  5. Press Ctrl+F5 to run the project. (If you get a “Cannot create Shadow Copy” error, close the browser and try again.)

    Click the Students tab to see the test data that the


    Seed

    method inserted. Depending on how narrow your browser window is, you’ll see the Student tab link in the top address bar or you’ll have to click the upper right corner to see the link.

Create your first app

On the Start page, select New Project. In the New project dialog box, select the Visual C# category on the left, then Web, and then select the ASP.NET Web Application (.NET Framework) project template. Name your project “MvcMovie” and then choose OK.

In the New ASP.NET Web Application dialog, choose MVC and then choose OK.

Visual Studio used a default template for the ASP.NET MVC project you just created, so you have a working application right now without doing anything! This is a simple “Hello World!” project, and it’s a good place to start your application.

Press F5 to start debugging. When you press F5, Visual Studio starts IIS Express and runs your web app. Visual Studio then launches a browser and opens the application’s home page. Notice that the address bar of the browser says

localhost:port#

and not something like

example.com

. That’s because

localhost

always points to your own local computer, which in this case is running the application you just built. When Visual Studio runs a web project, a random port is used for the web server. In the image below, the port number is 1234. When you run the application, you’ll see a different port number.

Right out of the box this default template gives you

Home

,

Contact

, and

About

pages. The image below doesn’t show the Home, About, and Contact links. Depending on the size of your browser window, you might need to click the navigation icon to see these links.

The application also provides support to register and log in. The next step is to change how this application works and learn a little bit about ASP.NET MVC. Close the ASP.NET MVC application and let’s change some code.

For a list of current tutorials, see MVC recommended articles.

CỰC NÓNG: SON HEUNG MIN Đ.Á.N.H NHAU VỚI LEE KANG IN Ở ASIAN CUP KHIẾN ĐT HQ BỊ LOẠI
CỰC NÓNG: SON HEUNG MIN Đ.Á.N.H NHAU VỚI LEE KANG IN Ở ASIAN CUP KHIẾN ĐT HQ BỊ LOẠI

Lập trình website với ASP.Net MVC cơ bản

Danh sách bài học

Dẫn nhập

Qua bài giới thiệu tổng quát về ASP.Net MVC đầu tiên, các bạn đã phần nào hiểu được cấu trúc cũng như cách thức hoạt động của nó.

Tuy nhiên, đã là lập trình thì không thể không thực hành, vì vậy trong bài học ngày hôm nay, mình sẽ hướng dẫn do các bạn cách tạo 1 project ASP.Net MVC và chúng ta sẽ làm 1 ví dụ đơn giản nhưng khá kinh điển đó là xuất câu “Hello Howktem”, qua ví dụ này các bạn sẽ nắm rõ về cách hoạt động của ASP.Net MVC bây giờ chúng ta cùng đi vào bài học nhé.

Nội dung

Để đọc hiểu bài này tốt nhất các bạn nên có kiến thức cơ bản về các phần:

  • Biết cách cài đặt Visual Studio bản 2012 trở lên, nếu chưa biết hay chưa cài đặt được thì các bạn tham khảo qua bài này nhé: Cài đặt môi trường phát triển (IDE) Visual studio 2015
  • Đã đọc qua bài: Giới thiệu tổng quan về công nghệ web ASP.Net MVC
  • Biết C# căn bản là 1 lợi thế, tuy nhiên nếu chưa có thì cũng không sao, các bạn sẽ được hướng dẫn cụ thể.

Trong bài học này, chúng ta sẽ cùng tìm hiểu các vấn đề:

  • Hướng dẫn tạo 1 project ASP.Net MVC, giải thích cấu trúc và vai trò của View, Controller
  • Xuất câu “Hello Howktem” sử dụng ASP.Net MVC

Feedback

Submit and view feedback for

Tạo website ASP.NET MVC đơn giản (P1)

Bài đăng này đã không được cập nhật trong 2 năm

Dựa trên nền tảng ASP.NET, ASP.NET MVC là một framework được phát triển bởi Microsoft, cho phép chúng ta xây dựng ứng dụng web theo mô hình MVC: (Model, View và Controller). Sau đây, mình sẽ hướng dẫn các bạn cách tạo một website ASP.NET MVC đơn giản bằng Visual Studio 2019 nhé.

Tạo một project ASP.NET bằng Visual Studio 2019

Đầu tiên, sau khi mở VS 2019, chọn File -> New -> Project, một cửa sổ New Project sẽ hiện lên. Trong cửa sổ này, bạn tìm kiếm và chọn ASP.NET core Web App (Model-View-Controller) với ngôn ngữ là C#.

Sau đó bạn chọn Next và đặt tên cho ứng dụng web của mình. Ở đây, mình đặt tên ứng dụng của mình là “My book”.

Tiếp tục chọn Next và chuyển tới cửa sổ lựa chọn phiên bản. Các bạn có thể lựa chọn các phiên bản .NET core 2.1,* .NET core 3.1* hay .NET core 5.0 và một số tùy chọn khác tùy theo phiên bản .NET mà bạn đã chọn.

Sau đó, bạn chọn Create để tạo web app. Visual Studio sẽ tự động tạo một template mặc định cho ứng dụng ASP.NET MVC bạn vừa tạo ra. Trong ứng dụng mặc định đa được tạo, có 2 trang chính Home và Privacy nằm thanh menu.

Để có thể xem được cấu trúc thư mục web bằng cách mở Solution Explorer (View -> Solution Explorer hoặc phím tắt Ctrl + Alt + L).

Cấu trúc Solution Explorer

Mọi Solution chứa 3 folder chính là Dependencies, Properties và* wwwroot*

Learn Visual Studio Code Editor for ASP.NET MVC Application - Complete Tutorial
Learn Visual Studio Code Editor for ASP.NET MVC Application – Complete Tutorial

Next steps

In this tutorial, you:

  • Created an MVC web app
  • Set up the site style
  • Installed Entity Framework 6
  • Created the data model
  • Created the database context
  • Initialized DB with test data
  • Set up EF 6 to use LocalDB
  • Created controller and views
  • Viewed the database

Advance to the next article to learn how to review and customize the create, read, update, delete (CRUD) code in your controllers and views.

Create the data model

Next you’ll create entity classes for the Contoso University application. You’ll start with the following three entities:

Course <-> Enrollment <-> Student

Entities Relationship
Course to Enrollment One-to-many
Student to Enrollment One-to-many

There’s a one-to-many relationship between

Student

and

Enrollment

entities, and there’s a one-to-many relationship between

Course

and

Enrollment

entities. In other words, a student can be enrolled in any number of courses, and a course can have any number of students enrolled in it.

In the following sections, you’ll create a class for each one of these entities.

Note

If you try to compile the project before you finish creating all of these entity classes, you’ll get compiler errors.

The Student entity

  • In the Models folder, create a class file named Student.cs by right-clicking on the folder in Solution Explorer and choosing Add > Class. Replace the template code with the following code:


    using System; using System.Collections.Generic; namespace ContosoUniversity.Models { public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection

    Enrollments { get; set; } } }

The

ID

property will become the primary key column of the database table that corresponds to this class. By default, Entity Framework interprets a property that’s named

ID

or classname

ID

as the primary key.

The

Enrollments

property is a navigation property. Navigation properties hold other entities that are related to this entity. In this case, the

Enrollments

property of a

Student

entity will hold all of the

Enrollment

entities that are related to that

Student

entity. In other words, if a given

Student

row in the database has two related

Enrollment

rows (rows that contain that student’s primary key value in their

StudentID

foreign key column), that

Student

entity’s

Enrollments

navigation property will contain those two

Enrollment

entities.

Navigation properties are typically defined as

virtual

so that they can take advantage of certain Entity Framework functionality such as lazy loading. (Lazy loading will be explained later, in the Reading Related Data tutorial later in this series.)

If a navigation property can hold multiple entities (as in many-to-many or one-to-many relationships), its type must be a list in which entries can be added, deleted, and updated, such as

ICollection

.

The Enrollment entity

  • In the Models folder, create Enrollment.cs and replace the existing code with the following code:


    namespace ContosoUniversity.Models { public enum Grade { A, B, C, D, F } public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } }

The

EnrollmentID

property will be the primary key; this entity uses the classname

ID

pattern instead of

ID

by itself as you saw in the

Student

entity. Ordinarily you would choose one pattern and use it throughout your data model. Here, the variation illustrates that you can use either pattern. In a later tutorial, you’ll see how using

ID

without

classname

makes it easier to implement inheritance in the data model.

The

Grade

property is an enum. The question mark after the

Grade

type declaration indicates that the

Grade

property is nullable. A grade that’s null is different from a zero grade — null means a grade isn’t known or hasn’t been assigned yet.

The

StudentID

property is a foreign key, and the corresponding navigation property is

Student

. An

Enrollment

entity is associated with one

Student

entity, so the property can only hold a single

Student

entity (unlike the

Student.Enrollments

navigation property you saw earlier, which can hold multiple

Enrollment

entities).

The

CourseID

property is a foreign key, and the corresponding navigation property is

Course

. An

Enrollment

entity is associated with one

Course

entity.

Entity Framework interprets a property as a foreign key property if it’s named
(for example,

StudentID

for the

Student

navigation property since the

Student

entity’s primary key is

ID

). Foreign key properties can also be named the same simply (for example,

CourseID

since the

Course

entity’s primary key is

CourseID

).

The Course entity

  • In the Models folder, create Course.cs, replacing the template code with the following code:


    using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public virtual ICollection

    Enrollments { get; set; } } }

The

Enrollments

property is a navigation property. A

Course

entity can be related to any number of

Enrollment

entities.

We’ll say more about the DatabaseGeneratedAttribute attribute in a later tutorial in this series. Basically, this attribute lets you enter the primary key for the course rather than having the database generate it.

EP 1 Complete Employees Management System Using ASPNET Core MVC, EF Core,SQL|AdminLTE| Perform CRUD💥
EP 1 Complete Employees Management System Using ASPNET Core MVC, EF Core,SQL|AdminLTE| Perform CRUD💥

2.Dependencies

Trong thư mục Dependencies, chúng ta có thư mục Nuget chứa các Nuget Packages đang sử dụng. Visual Studio sử dụng Nuget Packages để quản lý tất cả các dependencies phía server. Có 3 cách để tải Nuget Package vào project:

  • Chỉnh sửa thẳng file .csproj
  • Sử dụng Nuget Package Manager
  • Qua lệnh Package Manager Console

View the database

When you ran the Students page and the application tried to access the database, EF discovered that there was no database and created one. EF then ran the seed method to populate the database with data.

You can use either Server Explorer or SQL Server Object Explorer (SSOX) to view the database in Visual Studio. For this tutorial, you’ll use Server Explorer.

  1. Close the browser.

  2. In Server Explorer, expand Data Connections (you may need to select the refresh button first), expand School Context (ContosoUniversity), and then expand Tables to see the tables in your new database.

  3. Right-click the Student table and click Show Table Data to see the columns that were created and the rows that were inserted into the table.

  4. Close the Server Explorer connection.

The ContosoUniversity1.mdf and .ldf database files are in the %USERPROFILE% folder.

Because you’re using the

DropCreateDatabaseIfModelChanges

initializer, you could now make a change to the

Student

class, run the application again, and the database would automatically be re-created to match your change. For example, if you add an

EmailAddress

property to the

Student

class, run the Students page again, and then look at the table again, you’ll see a new

EmailAddress

column.

Introduction to ASP.NET Core MVC (.NET 8)
Introduction to ASP.NET Core MVC (.NET 8)

# Setup project ASP.NET MVC 5

Tạo một project để test thử nào mọi người, trong Visual Studio 2019 cũng khá tuyệt với đấy nhé, nói chung đẹp,…

Bạn chọn ASP.NET Web Application nhé, nhớ chọn C# , tiếp tục bước tiếp theo bạn chọn Version Framework mà mình dùng là được, sau khi tạo xong, bạn tạo cho mình file Controller trong Project vừa tạo như sau

Mình sẽ tạo file HomeController.cs trong thư mục Controllers, sau khi tạo xong ta tiến hành tạo Layout cho giao diện. Đầu tiên các bạn vào Views tạo thư mục Shared, sau đó add một layout như hình bên dưới đây. Layout này mình dùng để cấu hình cho từng file hiển thị ngoài website, các bạn có thể hiểu là một file Index.cshtml nó sẽ kế thừa giao diện từ một Layout, Nếu bạn có xem qua lập trình Laravel Framework thì nó cũng kế thừa từ một Layout, để chúng ta đở tốn code và dễ chỉnh sửa giao diện sao này.

Ok, sao khi tạo layout cho project xong, bạn mở file HomeController.cs tại function index() bạn thực hiện add một View như sau:click right index()->chọn Add View Chọn tới Layout mà mình vừa tạo bên trên

Bạn sẽ được một file Index.cshtml trong thư mục Views/Home/Index.cshtml.Home(HomeController), Index.cshtml (function Index() trong HomeController) nhé mọi người , Tiếp theo bạn mở file HomeController.cs lên và chỉnh sửa như sau

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVC5_HelloWorld.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { ViewBag.title = “MVC5 – Hello World”; return View(); } } }

Chúng ta thiết lập ViewBag.title dùng để chèn một chuổi dữ liệu hay một mảng dữ liệu mà ta muốn nó được hiện thị ngoài View, bạn có thể kết hợp với LingQ nhé, bạn có thể xem ví dụ dưới đây

//HomeController.cs var data = (from s in _db.users select s).ToList(); View.Bag = data; return View() //Views/Home/Index.cshtml @foreach(var result in ViewBag.data){

@result.name


@result.created_at

}

Trên là ví dụ nếu bạn muốn lấy dữ liệu trong SQL SERVER , để hiện thị ra ngoài View

Tiếp tục bạn vào Views/Home/Index.cshtml mở lên và chỉnh sửa lại như sau:

@{ ViewBag.Title = “Index”; Layout = “~/Views/Shared/_LayoutPage1.cshtml”; }

Set up the site style

A few simple changes will set up the site menu, layout, and home page.

  1. Open Views\Shared\_Layout.cshtml, and make the following changes:

    • Change each occurrence of “My ASP.NET Application” and “Application name” to “Contoso University”.
    • Add menu entries for Students, Courses, Instructors, and Departments, and delete the Contact entry.

    The changes are highlighted in the following code snippet:


    <br /> @ViewBag.Title - Contoso University<br />
    @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")

    @Html.ActionLink("Contoso University", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

    • @Html.ActionLink("Home", "Index", "Home")
    • @Html.ActionLink("About", "About", "Home")
    • @Html.ActionLink("Students", "Index", "Student")
    • @Html.ActionLink("Courses", "Index", "Course")
    • @Html.ActionLink("Instructors", "Index", "Instructor")
    • @Html.ActionLink("Departments", "Index", "Department")
    @RenderBody()

    © @DateTime.Now.Year - Contoso University

    @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)


  2. In Views\Home\Index.cshtml, replace the contents of the file with the following code to replace the text about ASP.NET and MVC with text about this application:


    @{ ViewBag.Title = "Home Page"; }

    Contoso University

    ASP.NET Core MVC 6.0 Full Course (Beginner)
    ASP.NET Core MVC 6.0 Full Course (Beginner)

    Initialize DB with test data

    Entity Framework can automatically create (or drop and re-create) a database for you when the application runs. You can specify that this should be done every time your application runs or only when the model is out of sync with the existing database. You can also write a

    Seed

    method that Entity Framework automatically calls after creating the database in order to populate it with test data.

    The default behavior is to create a database only if it doesn't exist (and throw an exception if the model has changed and the database already exists). In this section, you'll specify that the database should be dropped and re-created whenever the model changes. Dropping the database causes the loss of all your data. This is generally okay during development, because the

    Seed

    method will run when the database is re-created and will re-create your test data. But in production you generally don't want to lose all your data every time you need to change the database schema. Later you'll see how to handle model changes by using Code First Migrations to change the database schema instead of dropping and re-creating the database.

    1. In the DAL folder, create a new class file named SchoolInitializer.cs and replace the template code with the following code, which causes a database to be created when needed and loads test data into the new database.


      using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using ContosoUniversity.Models; namespace ContosoUniversity.DAL { public class SchoolInitializer : System.Data.Entity. DropCreateDatabaseIfModelChanges

      { protected override void Seed(SchoolContext context) { var students = new List

      { new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")}, new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")}, new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")}, new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")}, new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")}, new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")}, new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")}, new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")} }; students.ForEach(s => context.Students.Add(s)); context.SaveChanges(); var courses = new List

      { new Course{CourseID=1050,Title="Chemistry",Credits=3,}, new Course{CourseID=4022,Title="Microeconomics",Credits=3,}, new Course{CourseID=4041,Title="Macroeconomics",Credits=3,}, new Course{CourseID=1045,Title="Calculus",Credits=4,}, new Course{CourseID=3141,Title="Trigonometry",Credits=4,}, new Course{CourseID=2021,Title="Composition",Credits=3,}, new Course{CourseID=2042,Title="Literature",Credits=4,} }; courses.ForEach(s => context.Courses.Add(s)); context.SaveChanges(); var enrollments = new List

      { new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A}, new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C}, new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B}, new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B}, new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F}, new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F}, new Enrollment{StudentID=3,CourseID=1050}, new Enrollment{StudentID=4,CourseID=1050,}, new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F}, new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C}, new Enrollment{StudentID=6,CourseID=1045}, new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A}, }; enrollments.ForEach(s => context.Enrollments.Add(s)); context.SaveChanges(); } } }




      The


      Seed

      method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. For each entity type, the code creates a collection of new entities, adds them to the appropriate

      DbSet

      property, and then saves the changes to the database. It isn't necessary to call the

      SaveChanges

      method after each group of entities, as is done here, but doing that helps you locate the source of a problem if an exception occurs while the code is writing to the database.

    2. To tell Entity Framework to use your initializer class, add an element to the


      entityFramework

      element in the application Web.config file (the one in the root project folder), as shown in the following example:

      The


      context type

      specifies the fully qualified context class name and the assembly it's in, and the

      databaseinitializer type

      specifies the fully qualified name of the initializer class and the assembly it's in. (When you don't want EF to use the initializer, you can set an attribute on the

      context

      element:

      disableDatabaseInitialization="true"

      .) For more information, see Configuration File Settings.

      An alternative to setting the initializer in the Web.config file is to do it in code by adding a


      Database.SetInitializer

      statement to the

      Application_Start

      method in the Global.asax.cs file. For more information, see Understanding Database Initializers in Entity Framework Code First.

    The application is now set up so that when you access the database for the first time in a given run of the application, Entity Framework compares the database to the model (your

    SchoolContext

    and entity classes). If there's a difference, the application drops and re-creates the database.

    Note

    When you deploy an application to a production web server, you must remove or disable code that drops and re-creates the database. You'll do that in a later tutorial in this series.

    Hướng dẫn tạo 1 project ASP.Net MVC, giải thích cấu trúc và vai trò của View, Controller

    Đầu tiên các bạn mở Visual Studio lên, sau đó ngay tại thanh menu bạn chọn FILE >New >Project hoặc là cách đơn giản hơn là bạn nhấn tổ hợp phím tắt Ctrl + Shift + N

    Sau khi bạn làm xong bước trên, chúng ta tiếp tục làm theo như hình nhé.

    • Sau khi bảng hội thoại hiện lên, bạn chọn Visual C# > Web > ASP.NET Web Application.
    • Tại ô (4) bên cạnh vị trí Name bạn đặt tên cho project.
    • Chọn Browse… để chọn nơi lưu project.
    • Cuối cùng bạn chọn OK.

    Sau khi bạn nhấn OK ở bước trên thì sẽ có 1 bảng hội thoại xuất hiện các bạn làm theo hình nhé

    • Các bạn lưu ý trong phần Select a template có rất nhiều lựa chọn, tuy nhiên để học khóa học này các bạn chọn MVC nhé, sau đó chọn OK để kết thúc việc tạo project.

    Sau khi hoàn thành việc tạo project, bây giờ chúng ta cùng đi phân tích cấu trúc của nó nhé.

    • Như hình mình show ra cho các bạn ở phía trên, vùng màu đỏ chính là Controller, vùng màu xanh là Models và vùng màu tím chính là Views trong mô hình MVC
    • Tương ứng với 1 controller thì sẽ có 1 view đi kèm theo, mặc định project khi tạo gồm có 2 controller đó là Account và Home vì vậy các bạn sẽ thấy có 2 folder đó là Account và Home trong phần View. Do ban đầu chúng ta chưa truy xuất cơ sở dữ liệu nên models mình sẽ chưa đề cập đến trong bài học ngày hôm nay.

    Khi project được tạo ra thì chúng ta có thể chạy project lên brower, vậy để chạy được các bạn làm như sau:

    • Trên thanh menu bạn sẽ nhìn thấy nút mũi tên màu xanh, đây là nút giúp bạn Run project lên, tuy nhiên ban đầu nếu bạn nào thấy tại nút này không có hiển thị trình duyệt mặc định trong máy mình như cốc cốc, chrome, firefox … thì các bạn chọn Browse With..
    • Sau khi chọn, 1 hộp thoại hiện lên, đầu tiên các bạn chọn trình duyệt mà mình muốn sử dụng mặc định khi chạy project lên, sau đó các bạn chọn Set as Default, vậy là các bạn đã hoàn thành.
    • Để chạy project bạn click vào nút Run Project

    Giao diện hiển thị khi chạy thành công như hình

    Vậy có bạn nào tự hỏi là tại sao lại có màn hình này chạy lên khi chúng ta chạy project lên ban đầu không? Rất dễ hiểu các bạn ạ, các bạn cùng theo dõi giải thích phía dưới nhé

    Để giải thích cho lý do mà mình nêu ra ở phần trên thì trước tiên các bạn vào mục Controller.

    Sau đó các bạn chọn và mở HomeController lên thì sẽ thấy kết quả như hình dưới

    Khi vào HomeController thì bạn sẽ thấy màn hình như phía trên. Các bạn để ý nhé, trong Controller có cung cấp 1 phương thức có tên gọi là ActionResult. Phương thức này trả về rất nhiều kiểu dữ liệu khác nhau, và trong trường hợp này các bạn thấy kiểu trả về là View().

    • View() là 1 trong các kiểu dữ liệu được trả về từ hàm ActionResult , trong khuôn khổ bài này mình sẽ không phân tích rõ về phương thức ActionResult mà sẽ có bài hướng dẫn rất rõ về nội dung này.
    • Kiểu trả về View() dùng để hiển thị giao diện mà mình muốn xuất ra cho người dùng khi ActionResult được gọi lên.

    Ở phần trên mình có đề cập, 1 Controller sẽ có 1 View kèm theo, các bạn hãy xuống phần View mở folder đó ra.

    Như các bạn thấy, trong HomeController bao gồm 3 ActionResult đó là About, Contact, Index. Mà cả 3 ActionResult này đều trả về kiểu dữ liệu là View() vì vậy trong folder home sẽ cũng có 3 View tương ứng cho 3 ActionResult đó.

    Cụ thể khi ActionResult Index được gọi lên thì Index.cshtml sẽ được hiển thị, và 2 cái còn lại tượng tự như vậy. Bây giờ, bạn click vào Index.cshtml để xem nội dung của file này thì các bạn sẽ thấy nội dung của nó giống y chang nội dung được hiển thị khi chúng ta chạy project lên.

    Nhìn vào hình vẽ thì các bạn cũng thấy giao diện đó chính là do file Index.cshtml hiển thị, có nghĩa là ActionResult Index được gọi lên ban đầu, vậy lại có 1 câu hỏi đặt ra là tại sao trong HomeController gồm có 3 ActionResult mà cái Index lại được mặc định chạy đầu tiên mà không phài là About hay Contact? Các bạn chú ý nhé!

    • Các bạn mở folder App_Start > mở file RouteConfig.
    • Như các bạn thấy, trong RouteConfig tại 2 vị trí mà mình trỏ mũi tên vào thì đó là nguyên nhân khi các bạn chạy project lên là ActionResult Index được hiển thị mà không phải là About hay Contact.
    • Controller được gọi lên là HomeController, trong đó ActionResult Index được thực thi. Các bạn có thể thay đổi Controller và Action nào mà các bạn muốn mặc định chạy lên ban đầu.
    • Qua những giải thích đó thì các bạn đã hiểu về View, Controller cũng như cách hoạt động của chúng rồi, vậy để xuất câu “Hello Howkteam” chúng ta sẽ đi qua phần thứ 2 nhé
    ASP.NET Core MVC CRUD Operations using .NET 8 and Entity Framework Core - MVC For Beginners Tutorial
    ASP.NET Core MVC CRUD Operations using .NET 8 and Entity Framework Core - MVC For Beginners Tutorial

    Create the database context

    The main class that coordinates Entity Framework functionality for a given data model is the database context class. You create this class by deriving from the System.Data.Entity.DbContext class. In your code, you specify which entities are included in the data model. You can also customize certain Entity Framework behavior. In this project, the class is named

    SchoolContext

    .

    • To create a folder in the ContosoUniversity project, right-click the project in Solution Explorer and click Add, and then click New Folder. Name the new folder DAL (for Data Access Layer). In that folder, create a new class file named SchoolContext.cs, and replace the template code with the following code:


      using ContosoUniversity.Models; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace ContosoUniversity.DAL { public class SchoolContext : DbContext { public SchoolContext() : base("SchoolContext") { } public DbSet

      Students { get; set; } public DbSet

      Enrollments { get; set; } public DbSet

      Courses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove (); } } }



    Specify entity sets

    This code creates a DbSet property for each entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.

    Note

    You can omit the

    DbSet

    and

    DbSet

    statements and it would work the same. Entity Framework would include them implicitly because the

    Student

    entity references the

    Enrollment

    entity and the

    Enrollment

    entity references the

    Course

    entity.

    Specify the connection string

    The name of the connection string (which you'll add to the Web.config file later) is passed in to the constructor.


    public SchoolContext() : base("SchoolContext") { }

    You could also pass in the connection string itself instead of the name of one that is stored in the Web.config file. For more information about options for specifying the database to use, see Connection strings and models.

    If you don't specify a connection string or the name of one explicitly, Entity Framework assumes that the connection string name is the same as the class name. The default connection string name in this example would then be

    SchoolContext

    , the same as what you're specifying explicitly.

    Specify singular table names

    The

    modelBuilder.Conventions.Remove

    statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables in the database would be named

    Students

    ,

    Courses

    , and

    Enrollments

    . Instead, the table names will be

    Student

    ,

    Course

    , and

    Enrollment

    . Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.

    2.Thư mục wwwroot

    Các file tĩnh như HTML, CSS, Javascript hay hình ảnh hoặc các thư mục con của nó sẽ được lưu trư trong thư mục wwwroot

    Thư mục wwwroot được coi như thư mục root của website. Url của các thành phần trong thư mục root sẽ được đặt ngay sau domain. Ví dụ, domain của mình là

    http://cress1004.com/

    và trong thư mục wwwroot của mình có file image.png thì đường dẫn của file sau khi publish sẽ là

    http://cress1004.com/image.png

    .

    Toàn bộ code như C#, Razor file nên đặt ngoài thư mục này. Nếu muốn dùng tính năng này chúng ta cần sử dụng tính năng StaticFiles trong ASP.NET Core mà chúng ta sẽ tìm hiểu sau.

    Create Login Page in Asp.net (MVC 5 & SQL Server)
    Create Login Page in Asp.net (MVC 5 & SQL Server)

    Get started

    Start by installing Visual Studio 2017. Then, open Visual Studio.

    Visual Studio is an IDE, or integrated development environment. Just like you use Microsoft Word to write documents, you'll use an IDE to create applications. In Visual Studio, there's a list along the bottom showing various options available to you. There's also a menu that provides another way to perform tasks in the IDE. For example, instead of selecting New Project on the Start page, you can use the menu bar and select File > New Project.

    Xuất câu “Hello Howkteam” trong ASP.Net MVC

    Ở phần thứ nhất các bạn đã nắm được cách hoạt động của View, Controller rồi, bây giờ chúng ta cùng tạo 1 ví dụ đơn giản đó là xuất ra câu “Hello Howkteam” nhé.

    • Đầu tiên các bạn Controllers > Add > Controller
    • Tại giao diện này, các bạn chon MVC 5 Controller – Empty, sau đó chọn Add
    • Tại giao diện này, các bạn nhập tên Controller, mình để là Example rồi nhấn Add
    • Tiếp theo, để hiển thị câu “Hello Howkteam” chúng ta cần có View hiển thị, cách tạo View như sau
    • Bạn click phải chuột vào Index > chọn Add View. Sau đó các bạn làm theo các bước sau
    • Tại Template các bạn chọn Empty (without model), các bước còn lại làm theo hình nhé.
    • Sau khi tạo View Index xong thì để xuất câu “Hello Howkteam” thì bạn thay đổi 1 chút:
    • Tại thẻ bạn thay đổi nội dung bên trong: “Index” > “Hello Howkteam”. Sau đó các bạn vào RouteConfig trong App_Start để thay đổi Controller và Action > để chúng ta mặc định hiển thị trang chứa dòng chữ “Hello Howkteam” hiện lên đầu tiên
    • Tại controller bạn thay đổi nội dung bên trong Home > Example, còn action thì các bạn giữ nguyên giá trị là Index sau đó các bạn Run project lên kiểm tra, nếu màn hình chạy đúng như hình phía dưới thì các bạn đã tạo ví dụ thành công
    Student Management System Project Asp.net MVC
    Student Management System Project Asp.net MVC

    Keywords searched by users: visual studio 2019 mvc

    Mvc Web Application-Part 1 Visual Studio 2019 | Step-By-Step Asp.Net Mvc  Tutorial For Beginners - Youtube
    Mvc Web Application-Part 1 Visual Studio 2019 | Step-By-Step Asp.Net Mvc Tutorial For Beginners - Youtube
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Create First Mvc Web Application Using Visual Studio 2019 - Youtube
    Create First Mvc Web Application Using Visual Studio 2019 - Youtube
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Asp.Net Mvc 5 Hello World
    Asp.Net Mvc 5 Hello World
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    How To Create First Asp.Net Mvc Project In Visual Studio 2019 - Youtube
    How To Create First Asp.Net Mvc Project In Visual Studio 2019 - Youtube
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Visual Studio 2019 - Mvc Core - Part 01 - Hello World - Youtube
    Visual Studio 2019 - Mvc Core - Part 01 - Hello World - Youtube
    Mvc Pattern - Create Mvc Application | Mvc-Pattern Tutorial
    Mvc Pattern - Create Mvc Application | Mvc-Pattern Tutorial
    Tutorial: Create C# Asp.Net Core Web Application - Visual Studio (Windows)  | Microsoft Learn
    Tutorial: Create C# Asp.Net Core Web Application - Visual Studio (Windows) | Microsoft Learn
    Tạo 1 Project Asp.Net Mvc Đơn Giản Và Giải Thích Cấu Trúc, Vai Trò Của  View, Controller Trong Mô Hình Mvc. | How Kteam
    Tạo 1 Project Asp.Net Mvc Đơn Giản Và Giải Thích Cấu Trúc, Vai Trò Của View, Controller Trong Mô Hình Mvc. | How Kteam
    Asp.Net Core Mvc Newbie Here. I Am Trying To Create A New Controller In Visual  Studio 2019. Anytime I Click On Mvc Controller (Empty) Or Any Of The  Options, I Get Another
    Asp.Net Core Mvc Newbie Here. I Am Trying To Create A New Controller In Visual Studio 2019. Anytime I Click On Mvc Controller (Empty) Or Any Of The Options, I Get Another
    The Visual Studio 2019 Editor With The Mvc Template | Download Scientific  Diagram
    The Visual Studio 2019 Editor With The Mvc Template | Download Scientific Diagram
    Asp.Net Mvc 5 Install Bootstrap
    Asp.Net Mvc 5 Install Bootstrap
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Adding A View To An Mvc App | Microsoft Learn
    Adding A View To An Mvc App | Microsoft Learn
    Visual Studio 2019 - Mvc Core 3 - Part 03 - Viewbag - Youtube
    Visual Studio 2019 - Mvc Core 3 - Part 03 - Viewbag - Youtube
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    View In Asp.Net Mvc 5 (Phần 2) | Devmaster
    View In Asp.Net Mvc 5 (Phần 2) | Devmaster
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Get Started With Asp.Net Core Mvc | Microsoft Learn
    Tutorial: Get Started With Entity Framework 6 Code First Using Mvc 5 |  Microsoft Learn
    Tutorial: Get Started With Entity Framework 6 Code First Using Mvc 5 | Microsoft Learn
    Tutorial: Get Started With Entity Framework 6 Code First Using Mvc 5 |  Microsoft Learn
    Tutorial: Get Started With Entity Framework 6 Code First Using Mvc 5 | Microsoft Learn
    Tutorial: Get Started With Entity Framework 6 Code First Using Mvc 5 |  Microsoft Learn
    Tutorial: Get Started With Entity Framework 6 Code First Using Mvc 5 | Microsoft Learn
    Asp.Net Core Mvc Newbie Here. I Am Trying To Create A New Controller In Visual  Studio 2019. Anytime I Click On Mvc Controller (Empty) Or Any Of The  Options, I Get Another
    Asp.Net Core Mvc Newbie Here. I Am Trying To Create A New Controller In Visual Studio 2019. Anytime I Click On Mvc Controller (Empty) Or Any Of The Options, I Get Another
    Asp.Net Mvc 5 Hello World
    Asp.Net Mvc 5 Hello World

    See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *