Adding 2 IEnumerable Models in 1 View

I created a view that worked successfully with 1 view

@model IEnumerable<string> <ul> @foreach (var fName in Model) { var name = fName; var link = @Url.Content("~/Content/archives/mgamm/") + name.Replace(" ", "%20"); <li style="list-style:none; font-size:1.2em;"> <a href="@link">@name</a> </li> } </ul> @if (User.IsInRole("admin")) { <div> @using (Html.BeginForm("Index", "Archives", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="File" name="file" id="file" value="Choose File" /> <button type="submit">Upload</button> } </div> } 

With controller

 namespace plantationmvc.Controllers { public class ArchivesController : Controller { // // GET: /Archives/ public ActionResult Index() { var path = Server.MapPath("~/Content/archives/mgamm"); var dir = new DirectoryInfo(path); var files = dir.EnumerateFiles().Select(f => f.Name); return View(files); } [HttpPost] public ActionResult Index(HttpPostedFileBase file) { var path = Path.Combine(Server.MapPath("~/Content/archives/mgamm"), file.FileName); var data = new byte[file.ContentLength]; file.InputStream.Read(data, 0, file.ContentLength); using (var sw = new FileStream(path, FileMode.Create)) { sw.Write(data, 0, data.Length); } return RedirectToAction("Index"); } } } 

However, I wanted to add another fragment like this on the same page, but with different content content.

How to add another model to this page?

I just had a controller and View, so I created a ViewModel by creating 2 classes

 namespace plantationmvc.Models { public class ArchivesViewModel { public CommModel Model1 { get; set; } public MeetModel Model2 { get; set; } } public class CommModel { public IEnumerable<CommModel> } public class MeetModel { public IEnumerable<MeetModel> } } 

When I try to pass this into my view as @model IEnumerable<plantationmvc.Models.CommModel> , it says that it does not exist in the namespace.

+7
c # model-view-controller razor
source share
2 answers
 { public class ArchivesViewModel { public IEnumerable<CommModel> Model1 { get; set; } public IEnumerable<MeetModel> Model2 { get; set; } } public class CommModel { //properties of CommModel } public class MeetModel { //properties of Meet Model } } 

And add the view @model plantationmvc.Models.ArchivesViewModel

+7
source share

You need any type for your model that has two collections.

It can be your type (e.g. ArchivesViewModel from the answer above), or you can even use Tuple<T1, T2> .

Controler:

 public ActionResult Index() { var list1 = new[] { "1", "2", "3", "4", "5" }; var list2 = new[] { "10", "20", "30", "40", "50" }; var model = Tuple.Create<IEnumerable<string>, IEnumerable<string>>(list1, list2); return View(model); } 

Browse Index.schtml :

 @model Tuple<IEnumerable<string>, IEnumerable<string>> @foreach (var a in Model.Item1) { <h2>@a</h2> } @foreach (var b in Model.Item2) { <h3>@b</h3> } 
+2
source share

All Articles