Web
Analytics
ViewModel Example in asp.net MVC using Razor C# - Tutorial

For Consultation : +91 9887575540

Stay Connected :

View Model:

  • View Model is middle layer of view and model.
  • MVC

Some Question are emerge which are following





 

  1. Where I should put my presentation logic
  2. Where I should put my Data transmission logic
  3. How I can create a view with multiple models.

Practical Implementation:

Step 1: Create Two Model Classes( Employee.cs and User.cs)

Step 2: Create a controller names Employee

Step 3. Add Index(Index.cshtml) View

@{

ViewModel.Models.User CurrentUser = ViewBag.CurrentUser;

}

@CurrentUser.UserName

Employee Details
@Model.EmployeeName

 

@Model.Address

 

@Model.DataofBirth

 

@Model.Salary

 

Age:

@{

int age = DateTime.Now.Year – Model.DataofBirth.Year;

if(Model.DataofBirth>DateTime.Now.AddYears(-age))

{

age–;

}

@age

}

 

Salary:

@{

if (Model.Salary>20000)

{

@Model.Salary

}

else

{

@Model.Salary

}

}

 

 

Step 4. Run the Program and See the output

Step5 . Now We will create View Model

Create a Class (EmployeeVM) into Models folder and write following Code

Step 6: Make changes in Employee Controller as following

Step 7 Make Changes in Index.cshtml

@*@{

ViewModel.Models.User CurrentUser = ViewBag.CurrentUser;

}*@

@*

@CurrentUser.UserName

*@

@Model.userobj.UserName

Employee Details
@*

@Model.EmployeeName

 

@Model.Address

 

@Model.DataofBirth

 

@Model.Salary

*@

@Model.emp.EmployeeName

 

@Model.emp.Address

 

@Model.emp.DataofBirth

 

@Model.emp.Salary

@*

Age:

@{

int age = DateTime.Now.Year – Model.DataofBirth.Year;

if(Model.DataofBirth>DateTime.Now.AddYears(-age))

{

age–;

}

@age

}

*@

Age:@Model.Age

@*

Salary:

@{

if (Model.Salary>20000)

{

@Model.Salary

}

else

{

@Model.Salary

}

}

*@

Salary:

@Model.emp.Salary

 

 

Step 8 : Now Run and Execute the program and see the results.




Select your currency