Methods for returning multiple models or datasets from the same view using ASP. NET MVC

Source: Internet
Author: User
Tags actionlink

Asp.net MVC, by default, only one model can be returned at a time. If multiple datasets are called, viewdata can only be used for export. It seems very troublesome, you can implement the model extension method ( declare that this method is only applicable to MVC2, and supports generic type after mvc3. It is very convenient to directly use viewbag to pass it over. )

First, define a class in the controller. The content is as follows:
Public Class Blogmodel
{
Public Iqueryable <t_type> types { Get ; Private Set ;}
Public Iqueryable <t_post> posts { Get ; Private Set ;}
Public Blogmodel (iqueryable <t_type> types, iqueryable <t_post> posts)
{
This . Types = types;
This . Posts = posts;
}
}

To receive two iqueryable messages and then return

Iqueryable <t_type> types = From T In CB. t_typeSelect T;
Iqueryable <t_post> posts = ( From P In CB. t_post Orderby P. updatetime Select P). Take ( 10 );
// Viewdata ["message"] = "Welcome to ASP. net mvc! ";
Return View ( " Index " , New Blogmodel (types, posts ));

 

The first line of the View File to be referenced
<% @ Page Language = " C # " Masterpagefile = " ~ /Views/shared/site. Master " Inherits = " System. Web. MVC. viewpage <mvcblog. controllers. blogmodel> "   %>

Then you can use the types and posts datasets !!!
<% -- ArticleCategory -- %>
< Div ID = "Lcategory" >
< H4 >
< Span > My document category </ Span > </ H4 >
< Ul >
<% Foreach (VAR type in model. types)
{ %>
< Li > <% = Html. actionlink (type. typename, " # " ) %> </ Li >
<% } %>
</ Ul >
< BR />
</ Div >
<% -- Recent articles -- %>
< Div ID = "Llatest" >
< H4 >
< Span > Latest article list </ Span > </ H4 >
< Ul >
<% Foreach (VAR post in model. Posts)
{ %>
< Li > <% = Html. actionlink (post. title, " # " ) %> </ Li >
<% } %>
</ Ul >
< BR />
</ Div >

 

Related Article

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.