6

Create .NET MVC Web Application Using Visual Studio on Mac OS [Part 1]

 2 years ago
source link: https://www.codeproject.com/Articles/5318223/Create-NET-MVC-Web-Application-Using-Visual-Studio
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

I always wondered if I could use a full-fledged Mac with Mac OS to develop my projects, since I am a .NET developer, it was critically important for me to use windows. But since .NET core came out, I had the opportunity to use not only windows computers for development. At first I faced different problems, but gradually I solved them and now I am doing development using Visual Studio Mac. This series of articles consists of three articles, in which I will demonstrate step by step how to create a .NET Core MVC project, connect the project to an AWS RDS database, use the entity framework to create a connection between the database and the application, and all I will do on Mac OS and use Visual Studio for Mac, as well as Visual Studio code.

Create an MVC project

First, we need to create a simple MVC project. To do this, open Visual studio and create a new project (Image 1). Next, select .NET core 3.1 as Target Framework.

C81uJoZn-0l9T29wKaH4VhLGFFCDVxqHdnN1c_n04Gi0tUh-2u-LLAOf5GfAs_Qa_qI5d1kRtFzwm2JqcpkmFbGXCZS9vG61QSQQ3cfIAuE1aN4jwkhS8VbNmU-XUmutB0UdRAVq
Image 1 - Creating a new MVC project

Perhaps it will be a surprise for you, but here we will see a completely empty window, but do not worry, This is just closed by Solution Explorer. View-Layout-Solution Explorer. Here, as in Visual Studio windows, in MVC project we have Models, Controllers, Views folders.

Next, we need to connect services for the operation of our application. Since we will use Entity Framework for communication with the database, we will need everything connected with it. An example of connected services in the Image 2.

0C_mO3Vk0C3hIoA2hAdArFJRtIXwv_Yiduk63uuj9nPfJ_wst7iQhU-ZuU_Vr1pT272-arxv9KWmlMz2fLjzF6PfWuKR3zRqxertn72JGrcVmmZc7MmRzJYyCDuWdWwpJKIuNfJv
Image 2 - Connecting services

Second, let's create our model. It will be named Hospitals. Create a new class in Model folder. It has will have the following code:

Shrink ▲   Copy Code
public class Hospital

    {

        [Key]

        public int Hospitalid { get; set; }


        [StringLength(100)]

        [Display(Name = "Hospital name")]

        public string HospitalName { get; set; }


        [Required]

        [StringLength(100)]

        [Display(Name = "Dicision Maker")]

        public string Dicisionmaker { get; set; }


        [Required]

        [StringLength(100)]

        [Display(Name = "Email")]

        public string Email { get; set; }


        [Required]

        [StringLength(100)]

        [Display(Name = "Phone")]

        public string Phone { get; set; }

}

Next, let's create our context. Go to Solution Explorer and create a Data folder, and then an empty class. It should look like Image 3.

K3q33f27HppKrTxZjOSbj17r9c8eAjnTfNsSRn09h6iwy7BMASf9OFmj62AJHq3NQSi016VkVtqBHMGyVBpXF9h7EKZArsDRAjE978roVJpz-hxgJH3koQv1aPXeRWy8BLa_Py7W
Image 3 - Creating DBContext class

Further, in order to connect our application with the database, you need to add the following code to the DBContext class: Create class inherit from DbContext.

Copy Code
public class DBContext: DbContext

Then add a link to our table in the database

Copy Code
public DbSet <Hospital> Hospitals {get; set; }

Next, we will define the table with which there will be a connection when creating a model. A lot o people do not use it, but I use it becouse in my exeriance I have a lot of situations where model class name is different name in a database.

Copy Code
protected override void OnModelCreating (ModelBuilder modelBuilder)
 {
     modelBuilder.Entity <Hospital> () .ToTable ("Hospitals");
 }

Then we will indicate the location of our database, and for now we will leave it that way, and return to here the in the next steps.

Copy Code
protected override void OnConfiguring (DbContextOptionsBuilder options)
   => options.UseSqlServer ("");

Let's create a static method that will return a new context to us.

Copy Code
public static DBContext Create ()
{
    return new DBContext ();
}

As a result, you should get the code:

Shrink ▲   Copy Code
public class DBContext : DbContext

    {

        public DbSet<Hospital> Hospitals { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)

        {

            modelBuilder.Entity<Hospital>().ToTable("Hospitals");

        }


        protected override void OnConfiguring(DbContextOptionsBuilder options)

           => options.UseSqlServer("");


        public DBContext()

        {

        }


        public static DBContext Create()

        {

            return new DBContext();

        }


    }

We are now ready to create our controller. Next, we need to create three methods: show all records from the table, add a new record to the table and create an empty page to populate the model. I do not show it anymore, since the purpose of this article is to show the very principle of operation.
Let's create a new control and name it HospitalsController (Image 4) .

5079r7Q5Lp__tLx71vOzTlhjEyQ1XHRKiFdbhQG_ek6QGOpgx_h-X-Sx31MQlzbpE6DjNST9n47yI5FwkXCO5cb1VsYD3xixSpc30APoYi90Sh-WieKhhTRn3uGNnYwhPs84fkcG
Image 4 - Creating a new controller

Next, Let us inherit our class the Controller class

Copy Code
public class HospitalsController:Controller

Next, create database connection in the controller.

Copy Code
private DBContext _context;

And add code:

Copy Code
public HospitalsController()

{

    _context = new DBContext();

}


protected override void Dispose(bool disposing) => _context.Dispose();

Next, let's create three methods. The first one will display the list of entities.In this code, we read the values from the database and return them to the view, which we will create later (Index,Save,New). Add the following code:

Copy Code
[Route("Hospitals/Index")]

        public ActionResult Index()

        {

            var CustomersList = _context.Hospitals;

            return View("Index", HospitalsList);

        }

The next, create the second method will create a new entity. Add the following code:

Copy Code
public ActionResult New()

        {

            var hospital = new Hospital();

             return View("HospitalsForm", hospital);

        }

Next, create the third that will save a new entity. Let's add the following code:

Copy Code
public ActionResult Save(Hospital hospital)

        {

            if (!ModelState.IsValid)

            {

                var _hospital = hospital;                


                return View("CustomerForm", hospital);

            }


            _context.Hospitals.Add(hospital);


            _context.SaveChanges();


            return RedirectToAction("Index", "Hospitals");

        }

Finnaly, we have to do is add the views to our application.

Next, let's edit _Layout in the Shared folder.

ASP.NET
Copy Code
<li class = "nav-item">
 <a class="nav-link text-dark" asp-area="" asp-controller="Hospitals" asp-action="Index"> Hospitals </a>
</li>

Next, for our example, we do with two. views Visual Studio on Mac does not have standard functionality without connecting various extensions to immediately create a View from a controller (Image 5).

8NzI0uiAfpgMSGJm3auv0FEG1u4mIp7nNYZ5gMgMrjxD2akQj19mgo1rG9zt5fnjdfL3LHDaXWbVISa6tZx7qvEycEyYPAZls6cbVbkl80xueunME1XmHZM-6rEJOPbseXw_3qi-
Image 5 - We can not create View from controller

To create this, go to the View tab and create a new folder that has Hospitals. Next, create two view files - Index, HospitalsForm. It will display us a list and plus there will be a button with the creation of a new one.

Add the following code to Index:

ASP.NET
Shrink ▲   Copy Code
@model IEnumerable<My_Code_first.Models.Hospital>


@{ ViewBag.Title = "Hospitals";

                Layout = "~/Views/Shared/_Layout.cshtml"; }


<h2>Customers</h2>


<p>

    @Html.ActionLink("New Hospital", "New", "Hospitals", null, new { @class = "btn btn-primary" })

</p>


<table class="table">

    <tr>

        <th>

            Hospital ID

        </th>


        <th> Hospital Name</th>

        <th> Dicisionmaker</th>

        <th> Phone</th>

        <th> Email</th>


        @foreach (var hospital in Model)

        {

    <tr>

        <td>
            @Html.DisplayFor(hospitalId => hospital.Hospitalid)
        </td>

        <td>
            @Html.DisplayFor(hospitalName => hospital.HospitalName)
        </td>

        <td>
            @Html.DisplayFor(hospitalDicisionmaker => hospital.Dicisionmaker)
        </td>

        <td>
            @Html.DisplayFor(hospitalPhone => hospital.Phone)
       </td>

        <td>
            @Html.DisplayFor(hospitalEmail => hospital.Email)
        </td>


    </tr>}


    </table>

Next, the code is in HospitalForm.

ASP.NET
Shrink ▲   Copy Code
@model My_Code_first.Models.Hospital

@using (Html.BeginForm("Save", "Hospitals"))

{

    @Html.ValidationSummary()

    <div class="form-group">

        @Html.LabelFor(m => m.HospitalName)

        @Html.TextBoxFor(m => m.HospitalName, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.HospitalName)


    </div>


    <div class="form-group">

        @Html.LabelFor(m => m.Dicisionmaker)

        @Html.TextBoxFor(m => m.Dicisionmaker, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.Dicisionmaker)


    </div>


    <div class="form-group">

        @Html.LabelFor(m => m.Email)

        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.Email)


    </div>

    <div class="form-group">

        @Html.LabelFor(m => m.Phone)

        @Html.TextBoxFor(m => m.Phone, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.Phone)


    </div>


    <button type="submit" class="btn btn-primary"> Save </button>

    @Html.HiddenFor(m => m.Hospitalid)

    @Html.AntiForgeryToken()


}

For this step we are done.

Conclusion

This completes this article, we created a new .NET MVC application, created a model, a controller and a view. In addition, we prepared a context for creating a connection to the database.In the next article, I will show you how to link an application to a cloud database.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK