ASP.NET MVC 5 Hello World

I am building a simple example with ASP.NET MVC5. We can build various kinds of Web applications using ASP.NET MVC 5.

Today, I will share how to build a simple Web application project using ASP.NET MVC 5, with Visual Studio 2019.

Everyone can download it here.
 
Installing notes - When installing, make sure to open the Individual Components tab, and choose Class Designer and LINQ to SQL Tools.
 
Setup project ASP.NET MVC 5 
 
 
 
You choose ASP.NET Web Application. Next, you will choose the framework version.
 
After creating the project, add new HomeControler.cs file in the Controllers directory. 
 
 
 
 
 
 
 
Ok, now create the layout of the project.
  • Create Shared folder in directory Views
  • Create _LayoutPage1.cshtml file in Views/Shared directory
 
 
 
You've created the layout successfully!
 
Next open HomeController.cs, click-right function index()-> choose Add View.
 
 
 
 
 
You have a new Index.cshtml file in Views/Home/Index.cshtml directory.

Continue!
 
Open Controllers/HomeController.cs and configuration function index() using the folllowing below code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MVC5_HelloWorld.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         // GET: Home  
  12.         public ActionResult Index()  
  13.         {  
  14.             ViewBag.title = "MVC5 - Hello World";  
  15.             return View();  
  16.         }  
  17.     }  
  18. }  
We set ViewBage.title to insert a string of data or an array of data that we want to be displayed outside of View.

You can use LinQ for data access. You can see the following code below:
  1. //HomeController.cs  
  2. var data = (from s in _db.users select s).ToList();  
  3. ViewBag = data;  
  4. return View()  
  5.   
  6. //Views/Home/Index.cshtml  
  7. @foreach(var result in ViewBag.data){  
  8.   
  9.   <span>@result.name</span>  
  10.   <span>@result.created_at</span>  
  11. }  
The above is an example where we get data from a SQL Server database and display outside of the View. 
 
Continue to Views / Home / Index.cshtml and open up and edit the following:
  1. @{  
  2.     ViewBag.Title = "Index";  
  3.     Layout = "~/Views/Shared/_LayoutPage1.cshtml";  
  4. }  
  5.   
  6. <h2>@ViewBag.title</h2>  
That's it.
 
Build and run your project and test it.