ASP.NET MVC > Basics

Create new model in ASP.NET MVC

How to create a new Model in asp.net mvc?


ASP.NET MVC Model

Model is the representation of application entity and it generally contains properties corresponding to the database table fields. Apart from that it may also contains validation logics (validation attributes) and any other logics.

Model is the M of MVC.

How to create ASP.NET MVC Model?

Right click Models folder from the Solution Explorer and select Add > Class...

Write the name of the Model you want to create, in this case PersonalDetail and click Add. 

Creating model corresponding to database table

A class file named PersonDetail.cs is added into Models folder. Now, let’s assume that we want to create a Model corresponding to the following table in the database. Notice that database table name is also PersonalDetail.

In ideal scenario, the database table name should be plurised (like instead of PersonalDetail, it should be PersonalDetails).

To do that we need to create properties corresponding to the fields of the database table and our Model looks like below.

/Models/PersonalDetail.cs

using System; 
using System.Collections.Generic; 
using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication1.Models { public class PersonalDetail { [Key] [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int AutoId { get; set; }
[StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please write your LastName")] public string LastName { get; set; } public int Age { get; set; } [Display(Name = "Is Active?")]
public bool Active { get; set; } } }

Remember that we need to add last two namespaces in order to add attributes to the properties. Let’s talk about attributes added to the properties of this Model. 

The best way to add the namespace is press Ctrl + . by keeping the cursor on the attributes. It will give a IntelliSense as the probable namespace and then select the appropriate one.

ASP.NET Model validations attributes

Description of the attributes added to this Model. 

  • [Key] – Used to mark the property as Primary key
  • [DatabaseGenerated] – used to mark the field as database generated (auto increment field in the database) 
  • [StringLength] - used to limit the length of the characters allowed in this field 
  • [Required] – used to mark the property as mandatory 
  • [Display] – used to bring a description Label for the property when view is scaffold.
 Views: 21207 | Post Order: 7



Write for us






Hosting Recommendations