DEV Community

Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on • Updated on

ASP.NET MVC 5 Helllo World

Buiding a example simple with ASP.NET MVC5. we can see, many developer program ASP.NET MVC 5
Today, I will shared buiding way create project ASP.NET MVC 5, with program Visual Studio 2019
Everyone,can download here:https://docs.microsoft.com/en-gb/visualstudio/releases/2019/release-notes
Installing, note you tab open Individual Components, after then, you choose Class Designer and LINQ to SQL Tools

Setup project ASP.NET MVC 5
You create project
ASP.NET MVC 5 Helllo World - hoanguyenit.com
You choose ASP.NET Web Application, let's go, you can need choose Version Framework
After create success project, you can add news HomeControler.cs file in Controllers directory
ASP.NET MVC 5 Helllo World - hoanguyenit.com
ASP.NET MVC 5 Helllo World - hoanguyenit.com
ASP.NET MVC 5 Helllo World - hoanguyenit.com

Ok, Begin you create layout project

  • Create Shared folder in directory Views
  • Create _LayoutPage1.cshtml file in Views/Shared directory

ASP.NET MVC 5 Helllo World - hoanguyenit.com

you create layout razor success!, you open HomeController.cs, click-right function index()-> choose add view
ASP.NET MVC 5 Helllo World - hoanguyenit.com

ASP.NET MVC 5 Helllo World - hoanguyenit.com

You have new Index.cshtml file in Views/Home/Index.cshtml directory
Continue! you need to Controllers/HomeController.cs open it and configuration function index(), 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
    {
        // GET: Home
        public ActionResult Index()
        {
            ViewBag.title = "MVC5 - Hello World";
            return View();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

We set ViewBage.title to insert a string of data or an array of data that we want it to be displayed outside of View
You can using LinQ, you can see the following below

//HomeController.cs
var data = (from s in _db.users select s).ToList();
ViewBag = data;
return View()

//Views/Home/Index.cshtml
@foreach(var result in ViewBag.data){

  <span>@result.name</span>
  <span>@result.created_at</span>
}
Enter fullscreen mode Exit fullscreen mode

The above is an example if you want to retrieve data in SQL SERVER, to display outside the View

Continue to you Views / Home / Index.cshtml and open up and edit the following:

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

<h2>@ViewBag.title</h2>
Enter fullscreen mode Exit fullscreen mode

That's it, you can Run the project and test it out!
Post:

Top comments (0)