ASP. net mvc 3.0 Razor view how to display multiple objects

Source: Internet
Author: User

 

The Razor view model supports @ model to initialize the Page Object type, for example:

1 @ model FlashTravel. Models. Traveller>

It can also be a public enumerator that supports iteration:

1 @ model IEnumerable <FlashTravel. Models. Traveller>

When we only focus on rendering an object class, the implementation of MVC 3.0 is very powerful, and the Controller layer only needs two lines of code:

Public ActionResult Index ()

{

Var traveller = dbFlashTravel. Traveller. ToList ();

Return View (traveller );

}

The ToList () method returns the List <T> set, which Implements the (Implements) interface IEnumerable <out T>. Therefore, when the var variable traveller is passed to the View layer, you can use foreach for traversal:

@ Foreach (var item in Model ){

//......

}

 

A powerful framework is just to make simple things simpler. If the problem becomes a little complicated, most of them will be solved by smart brains. I like to visit area 42, the instant information function similar to Weibo on its homepage is quite interesting. I am also doing BS development, so I used MVC 3.0 to simulate a game.

The business model can be described as follows: a logged-on member can post a broken line (up to 142 characters), but the number of images that match the line is not limited (only one is provided during the test ), at the same time, it can be replied by other Members. Extract the most basic object from the description: Member (Traveller), Chat, ChatImage, and ChatReply)

Free images from VS2010:

 

Obviously, the ChatID field of the primary key of the object Chat is associated with the entity ChatImage (one-to-many) and the entity ChatReply (one-to-many ).

The ORM framework automatically maps database tables to entity classes with the same name (EF4.0 is also true). These entity classes are like building bricks and tiles, it has become the most basic object for assembling various business models. Based on the above analysis, it is clear that the fragmented business model has three basic entity classes involved: Chat, ChatImage, and ChatReply. To better express them, I name this business model ChatIntegration (fragmented synthesis) and encapsulate it using a ViewModel Pattern class:

Namespace FlashTravel. ViewModels

{

/// <Summary>

/// Combine fragmented ideas

/// </Summary>

Public class ChatIntegration

{

/// <Summary>

/// Fragment

/// </Summary>

Public Chat ChatHeader {set; get ;}

 

/// <Summary>

/// Fragment

/// </Summary>

Public IList <ChatImage> ChatImages {set; get ;}

 

/// <Summary>

/// Response

/// </Summary>

Public IList <ChatReply> ChatReplys {set; get ;}

}

}

The code above indicates that a single fragmented business model contains a broken body called ChatHeader, several pictures (plural), and several replies (plural ).

 

In general, the Model layer is often used as a link in a project (MVC or a traditional three-tier), just as the elementary school teacher taught us to write an article in eight styles: start first, next, describe a section, and then make an upper-and lower-section, then enter the description of the next section, and finally end with a summary section. The business model (ChatIntegration) Here is the same: In the first section, the Controller layer first fetches the data in the database (based on Linq to SQL) and stores it in the business model; In the second section, the business model will be thrown to the View layer page and presented through Razor engine traversal.

 

As mentioned above, we will do two things next: first, let's look down at the layer and see how the business model (ChatIntegration) in the middle gets the database data, and then look up, see how the data is traversed after the business model (ChatIntegration) is thrown to the View.

(1 .) at the lower layer, according to the MVC 3.0 "separation of concerns" idea, the code for accessing the database should adopt the Repository design mode, so that the Action in the Controller layer can obtain the dataset only by calling the relevant functions in the Repository layer, so as to smoothly pass the function return value to the View layer, although "conventions are greater than configurations" is very important, but as long as my streamlining has not broken the MVC Architecture, let's just "coupling". I will write the code for accessing the database directly in the Action named Index:

Public class ChatController: Controller

{

FlashTravelDataContext dbFlashTravel = new FlashTravelDataContext ();

 

Public ActionResult Index ()

{

// Query all broken ideas

Var chatIntegrationList = from chat in dbFlashTravel. Chat

Join chatImage in dbFlashTravel. ChatImage

On chat. ChatID equals chatImage. ChatID into chatImages

Join chatReply in dbFlashTravel. ChatReply

On chat. ChatID equals chatReply. ChatID into chatReplys

Select new ChatIntegration

{

ChatHeader = chat,

ChatImages = chatImages. ToList (),

ChatReplys = chatReplys. ToList ()

};

Return View (chatIntegrationList );

}

}

Through declarative Linq queries, we get all the broken read records in the current database (in practice, we want to filter by time [for example, only query for the last week] and display them by page, ignored here), no more code. You will see the second half of the nested join-based Linq query. You can directly define the attribute values in each fragmented model (select new ChatIntegation. As long as you assign a value to the ChatIntegation, The chatIntegrationList based on the generic set will all be affected. In the end, it will be passed to the View layer as a parameter of the View (object model.

 

(2) When you look up, the view layer will receive a set of business models with full data (ChatIntegation generic set ):

1 @ model IEnumerable <FlashTravel. ViewModels. ChatIntegration>

Next, the ChatIntegation set of the business model requires at least one foreach traversal to extract each ChatIntegation for further processing. Just as we assemble data at the Controller layer, as long as we encode a business model, every element based on a generic set will be affected.

Obviously, the first traversal will get three attributes in each element ChatIntegation: ChatHeader, ChatImages, and ChatReplys ),

We found that the image and the reply are a new sub-generic set, so we made the second-layer foreach traversal for the two of them :@{

ViewBag. Title = "Index ";

}

<H2>

Index

<P>

@ Html. ActionLink ("Create New", "Create ")

</P>

<Table>

@ Foreach (var item in Model)

{

<Tr>

<Td style = "width: 150px; text-align: center;">

@ Item. ChatHeader. NickName

</Td>

<Td style = "width: 350px; text-align: right;">

@ Item. ChatHeader. PublishTime

</Td>

</Tr>

<Tr>

<Td style = "width: 150px; text-align: center;">

@ Foreach (var image in item. ChatImages)

{

}

</Td>

<Td style = "width: 350px; text-align: left;">

@ Item. ChatHeader. Content

</Td>

</Tr>

<Tr>

<Td colspan = "2">

<Br/>

<Span style = "font-weight: bold;"> FeedBack </span>

<Hr/>

</Td>

</Tr>

Foreach (var reply in item. ChatReplys)

{

<Tr>

<Td colspan = "2">

<Table style = "width: 100%;">

<Tr>

<Td>

@ Reply. PublishTime | @ reply. NickName

</Td>

</Tr>

<Tr>

<Td>

@ Reply. Reply

</Td>

</Tr>

</Table>

</Td>

</Tr>

}

}

</Table>

 

The final result is:

<Script> </script>

 

After a Demo, there are still less than 50 lines of code that really need to be written, and the understanding of programming methods is still the most important.

It seems like water in the past few years.

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.