View Model

The view is simply takes the data to its corresponding Model or particular model. , But the View model basically allows us to show data from multiple places or multiple Models in single view.

Scope About Application :

Total no. of sales of a particular book.

For ViewModel we should create this:
  1. Author controller to add authors. 
  2. Books controller to add books
  3. Sales controller for sales

Author Class

Create author class --> named Author.cs
Now follow snapshots:


Book class:

Create book class --> named Book.cs
Code:


Sale class:

Create Sale class --> named Sale.cs
Code:


Now, After create classes --> build project --> create controllers.
Then The solution explorer should look like this: 


Create view model folder:


Give folder name --> "ViewModels", Then under this folder --> add a class --> give name "BookSales" .

Now open "BookController.cs" and pass Queries:
The Snapshot given below,


Now you can see the error <BookSales>, it is simply the error of Namespace.
you can easily resolve this: Please look at the Snapshot,


Rebuild the project:
Now create view, Call it Sales because we have method name Sales.

inside view add following code :

@Html.DisplayNameFor(model => model.BookName) and @Html.DisplayNameFor
(model => model.TotalSales)

It displays the column names.

@foreach (var item in Model)

Foreach helps us to store bulk data from Model to variable item to print each record separately. 

  @Html.DisplayFor(modelItem => item.BookName) 

Since we have all columns stored in items. For the loop's first go we get BookName at first row. Same goes for 2nd, 3rd up to final record in table. 

 @Html.DisplayFor(modelItem => item.TotalSales)


WE ARE DONE!
Thank you.....









































Post a Comment

Previous Post Next Post