Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a hybrid-model (with bits of other models) in ASP.NET MVC?
    text
    copied!<p>I've created an Audit table for an ASP.NET MVC application to track key changes and actions. I want to present the contents of this table to authorized users in an easily readable format on the view.</p> <p>The Audit table is (simplified) like so:</p> <pre><code>ID (int) | StaffID (int) | Action (string) | Timestamp (datetime) ----------------------------------------------------------------- 1987 | 27 | Delete entry: 9 | 2010-02-22 12:30:12 1988 | 34 | Add user: 912 | 2010-02-22 12:48:19 </code></pre> <p>So far I've just been presenting that using the default "List" view in MVC however we're getting towards the end of development and I'd like to tidy up this view a bit by showing staff names rather than StaffIDs. </p> <p>Initially, I'm using the approach of creating a "hybrid model" that contains both Audit and Staff and passing that to the view:</p> <pre><code>public class AuditModel { public AuditModel(List&lt;Audit&gt; AuditEntries, List&lt;Staff&gt; AllStaff) { this.Audit = AuditEntries; this.Staff = AllStaff; } public List&lt;Audit&gt; Audit { get; private set; } public List&lt;Staff&gt; Staff { get; private set; } } [AcceptVerbs("GET")] public ActionResult ViewAuditTrail() { var Audit = (from a in db.Audits orderby a.Timestamp descending select a).ToList(); var Staff = (from s in db.Staffs select s).ToList(); return View(new AuditModel(Audit, Staff)); } </code></pre> <p>But that leads to messiness in the view:</p> <pre><code>&lt;% foreach (var Entry in Model.AuditEntries) { var StaffDetails = Model.AllStaff.Where(s =&gt; s.ID == Entry.StaffID).SingleOrDefault(); /* output HTML */ } %&gt; </code></pre> <p>So I guess what I want to do is create a new model with the following attributes:</p> <ul> <li>ID (int) - Audit.ID</li> <li>StaffName (string) - Staff.ID [s => s.StaffID == Staff.ID]</li> <li>Action (string) - Audit.Action</li> <li>Timestamp (datetime) - Audit.Timestamp</li> </ul> <p>But I want to do this in the controller and pass it to the view as a ToList() so my view can be cleaner and simpler.</p> <p>Any tips?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload