Implementing View Model in ASP.net MVC


In this article I'm going to explain how to create ViewModel and how to pass ViewModel from Controller to View as a Strongly type view. In my previous posts I explained about ViewData and ViewBag in MVC which is not strongly typed because of it's object. But using ViewModel we can make it as strong type.

Implementing View Model in ASP.net MVC:


Summary:


In this article I'm going to explain how to create ViewModel and how to access the same in controller class.
Follow below steps to achieve our goal.
Step 1 : Create Folder
Create a new folder called "ViewModels" in the project solution.

Step 2 : Create StudentViewModel
Create a new class called "StudentViewModel" inside ViewModels folder as like below.

namespace MVCProject.ViewModels
{
public class StudentViewModel
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public string Course { get; set; }
public string UserName { get; set; }
}
}


Step 3 : Use ViewModel in Views
Open view and use below lines of code in top of the page.


@using MVCProject.ViewModels
@model StudentViewModel


Step 4 : Display the Data in the View
Use below code snippet in View.


@using MVCProject.ViewModels
@model StudentViewModel
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DemoView</title>
</head>
<body>
Hello @Model.UserName
<hr/>
<div>
<b>Student Details:</b>
<br/>
Student Id : @Model.StudentId <br/>
Student Name : @Model.StudentName <br/>
Course : @Model.Course
</div>
</body>
</html>



Step 5 : Create & Pass ViewModel

public ActionResult GetStudent()
{

StudentViewModel objStdVM = new StudentViewModel();
objStdVM.StudentId = "1";
objStdVM.StudentName = "Naveen";
objStdVM.Course = "MCA";
objStdVM.UserName = "Admin";

///strongly typed view
return View("DemoView",objStdVM);
}


Result :



1

Conclusion:


Hope this article will give you the brief description about how to handle ViewModel in MVC and how to pass ViewModel from Controller to View as a Strongly type view.


Article by naveensanagasetti
I hope you enjoyed to read my article, If you have any queries out of this then please post your comments.

Follow naveensanagasetti or read 139 articles authored by naveensanagasetti

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: