Use ViewModel to transmit multiple models to the view. viewmodelmodel
When developing ASP. net mvc, we will encounter this situation. We need to transmit multiple models from the Controller to the View at one time.
The implementation is simple, just create a collection class.
OK. Prepare some data in the database first, for example:
Create table [dbo]. [TableA] ([A] NVARCHAR (30) NULL, [B] NVARCHAR (30) NULL, [C] NVARCHAR (30) NULL) GOINSERT INTO [dbo]. [TableA] ([A], [B], [C]) VALUES ('a1', 'b1 ', 'c1'), ('a2', 'b2 ', 'c2 '), ('a3', 'b3', 'c3'), ('a4 ', 'b4', 'c4'), ('a5 ', 'b5 ', 'c5') gocreate procedure [dbo]. [usp_TableA_GetAll] ASSELECT [A], [B], [C] FROM [dbo]. [TableA] GOSource Code
Another copy of data:
Create table [dbo]. [TableB] ([X] DECIMAL () NULL, [Y] DECIMAL () NULL, [Z] DECIMAL () NULL) goinsert into [dbo]. [TableB] ([X], [Y], [Z]) VALUES (0.2, 0.3, 0.4), (1.2, 2.3, 3.4), (4.2, 5.3, 6.4) gocreate procedure [dbo]. [usp_TableB_GetAll] ASSELECT [X], [Y], [Z] FROM [dbo]. [TableB] GOSource Code
Return to the ASP. net mvc project and create two models:
TableA model:
TableB model:
Now you need to create two entities to obtain the database data:
TableAEntity:
TableBEntity:
Everything is ready. Go to the subject to implement the ViewModel class:
In the controller:
The following is the view implementation:
#2 the code is as follows:
Program running result:
The key part of this article is to create another ViewModel class and add relevant models with attributes to the class. Below is a review:
This method is equivalent to writing dead. If another model is added or deleted, You have to modify this ViewModel class.