We know that in Asp.net mvc3, the controller can only transmit one model to the page at a time, but sometimes we need to transmit multiple models to the view. What should we do at this time...
I have not found a method that can be passed to view more than one model. However, we can create a class for the models you want to pass, in this way, you can include all the data you want to transmit to this class, and then pass the large model to the view. Simply put, a large model contains many small models, and then the large model is passed to the view. The Code is as follows:
Assume that the user is the class of the small model you want to upload. The Code is as follows:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace upload.Models{ public class User { public int ID { get; set; } public string Code { get; set; } public string Name { get; set; } }}
Create a new viewmodels class with the following content:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace upload.Models{ public class ViewModels { public User user1 { get; set; } public User user2 { get; set; } }}
Now, in the controller, you need to pass two user entities to the view. You can write the following code:
Public actionresult index () {viewbag. Message = "Welcome to ASP. net mvc! "; User user1 = new models. user (); User user2 = new models. user (); user1.id = 1; user1.code = "code1"; user1.name = "name1"; user2.id = 2; user2.code = "code2"; user2.name = "name2 "; viewmodels model = new viewmodels (); Model. user1 = user1; model. user2 = user2; return view (model );}
This Code contains the entity user1 and user2 of two users in a large model. Of course, you can also upload two instances of different classes to the big model.
The following is the view code. You can click it out directly...
<P> for more information about ASP. for more information about net MVC, visit <a href = "http://asp.net/mvc" Title = "ASP. net MVC Website "> http://asp.net/mvc </a>. <Label> user1 @ model. user1.id </label> <label> user1 @ model. user1.code </label> <label> user1 @ model. user1.name </label> <label> user2 @ model. user2.id </label> <label> user2 @ model. user2.code </label> <label> user2 @ model. user2.name </label> </P>
Now, you can run it.