Monday, March 4, 2019

Adding Model class to Asp.Net Core MVC

In the previous post we saw a basic Hello Word sample for MVC application using Asp.Net core. Let us now do some more improvement to the example and add a Model class to the project. Model is a Domain object or Business object which contains properties to represent the object. For example Product is a model class which contains properties like ProductName, Number, Cost etc.

Model is one of the layers of the MVC architecture, in MVC model deals with the data / structure of the business objects. Model objects are populated in the controller and passed on to the View layer for display. Let us not add a Model class Product to the MVC project. To do this right click on Model folder -> Add -> click on Class. Let us name our class Product.cs. Add the following code to the Model class.

    public class Product
    {
        public Product(int id, string name, string number, double cost)
        {
            this.ProductID = id;
            this.Name = name;
            this.ProductNumber = number;
            this.Cost = cost;
        }
        public int ProductID { get; set; }
        public string Name { get; set; }
        public string ProductNumber { get; set; }
        public double Cost { get; set; }
    }

Notice that we have a constructor in our model class, this is not mandatory always we have added a constructor since we will be populating static values to the model object in the controller and pass it on to the view.


Search Flipkart Products:
Flipkart.com

No comments: