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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MVC5_HelloWorld.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- ViewBag.title = "MVC5 - Hello World";
- return View();
- }
- }
- }
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:
-
- var data = (from s in _db.users select s).ToList();
- ViewBag = data;
- return View()
-
-
- @foreach(var result in ViewBag.data){
-
- <span>@result.name</span>
- <span>@result.created_at</span>
- }
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:
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_LayoutPage1.cshtml";
- }
-
- <h2>@ViewBag.title</h2>
That's it.
Build and run your project and test it.