I want my View to be as follows:
@model MyProgram.Models.DocumentList
@{
ViewBag.Title = "View1";
}
@foreach (MyProgram.Models.Document doc in Model.GetDocs())
{
<p>doc.Content</p>
}
This leads me to believe I need a Model that contains a list of another Model. So in a project containing nothing but this I would have:
/Model/DocumentList.cs
/Model/Document.cs
Is this correct or is there a better way?
Use View Models that way you can pass as many models to your view as it needs. I also use view models to handle the validation of POSTs etc. So in your case you can do something like:
Your View Model
public class MyViewModel
{
public string PageTitle { get; set; }
public DocumentList DocList { get; set; }
// You could use your DocumentList object here, or if you
// don't want to, just pass a List<T> of Document
public List<Document> DocList { get; set; }
}
Your View
@model MyViewModel
@{
ViewBag.Title = Model.PageTitle;
}
@foreach (var doc in Model.DocList)
{
<p>doc.Content</p>
}
There's MUCH more to MVC than this though, such as Display and Editor Templates so I'd have a look online for some good tutorials that cover the MVC essentials.
Edit
To be fair, having read this back you're already kind of following this principle it's just that DocumentList
is your view model (and you don't really need a GetDocs
method, just have a collection property, unless you're performing logic on the collection before returning that is).
Hopefully this answer helps clarify a few things for you though?
It depends on your needs. If you only have need a document model list in you view, I'd go only with a Document
model and changing the passed view model to:
@model List<MyProgram.Models.Document>
@{
ViewBag.Title = "View1";
}
@foreach (MyProgram.Models.Document doc in Model)
{
<p>doc.Content</p>
}
But if you need more properties or methods in your view, than I'd go with a view model containing a List<MyProgram.Models.Document>
and the other properties.
@model DocumentsViewModel
@{
ViewBag.Title = "View1";
}
@foreach (MyProgram.Models.Document doc in Model.DocumentList)
{
<p>doc.Content</p>
}
Model:
public class DocumentsViewModel
{
public List<MyProgram.Models.Document> DocumentList {get; set;}
... other properties
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With