Use ViewModel to transmit multiple models to the view. viewmodelmodel

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.