|
MVC model is basically a C# or VB.NET class. A model
is accessible by both controller
and view. A model can be
used to pass data from controller
to view. A view can use model to
display data in page.
We can add Model as depicted in a
figure below:
Right Click on Model Folder
à
Add
à Class.

After selecting Class option, change the class name if you
want. Here I change it into ModelClass.cs
Then click on Add button.

After adding a class, you must also have to know the
functionality of that class. In Model class we can implements properties,
methods and validations attribute etc. according to our need. We can perform all
the programming operation in the Class as we did earlier in various programming
languages.
In this class I had created two properties i.e.
FirstName and
LastName. At the above of both property I also created various (Required,
StringLength, RegularExpression) attribute that put various validation on
properties.
Instead of properties and methods I also create a
boolean method named IsExist that
returns either true or false when invoked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using
System.ComponentModel.DataAnnotations;
namespace FisrtMVCApp.Models
{
public class
ModelClass
{
[Required(ErrorMessage="First Name Required:")]
[DisplayName("Enter
First Name:")]
[StringLength(30, ErrorMessage =
":Less than 30 characters")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage =
"Special Characters
not allowed")]
public string
FirstName
{
get;
set;
}
[Required(ErrorMessage
= "First Name Required:")]
[DisplayName("Enter
Last Name:")]
[StringLength(30, ErrorMessage =
":Less than 30 characters")]
[RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage =
"Special Characters
not allowed")]
public string
LastName
{
get;
set;
}
public bool
IsExist()
{
return false;
}
}
By creating above
Model class, we can understand and can easily implement the functionality of
Model in MVC ASP.NET.
|