• How to Create a Model in ASP.NET MVC

    by  • January 1, 2016 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET MVC • 0 Comments

    Model is the most important part of the application. Model is going to describe the data and how we allow users to interact with it. We are going to design our model based on how the user expecting that model to be.

    Model is just a class. Model is just creating a class and defining its properties and methods. By convention we should have model inside the model folder. To create a model in MVC , we right click on model folder then click on add and then click on class. As shown in the figure below;

    modelfolder  addingClass booksclass


    We create a class book and define its properties in the class block. Property defines attributes of a class.We can set their attributes and we can retrieve the attributes as well. Lets look at the code given below;

    In the above code we are defining four properties of book that are ‘AuthorName’, ‘Title’,’Publisher’,’ PublishDate’  with the get and set method ({get; set; }). These are basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. The code above is automatically implemented properties where the compiler is adding a backing field. We can write the code our self though. For example, the Title property you’ve declared is like this;

    Now in the Controller in MVC or in the Main Method of C# , we can create instance (object) of class and then add properties of of books in that instance as shown below;

    Now in the Index View , we can access the properties of book class by razor syntax as shown below code

    This is strongly typed view so in the above code we access the properties of model with razor syntax @Model followed by . sign. When we write . sign, intellisense shows all property of the model.

    Best WordPress Themes and Plugins with Great Team and Support!

    Leave a Reply