asp.net-mvc-3model-binding

MVC 3 - Binding to a customised anonymous type linq query


How can we make the following example work with an anonymous type result set formed of select new {...}

Controller:

public ActionResult Index()
{
    var myJobs = from j in db.Jobs where j.deleted == false select j;
    //Need to REPLACE myJobs WITH a complex query
    return View(myJobs.ToList());
}

Index View:

@model IEnumerable<MyProj.Models.Jobs> //NOT SURE WHAT TO DO HERE
@{
    ViewBag.Title = "Jobs";
}
<table>
<tr>
    <th>
        Job-No
    </th>
    <th>
        Job-Name
    </th>
</tr>
@foreach (var item in Model)
    {
        <tr>
            <td>@String.Format("{0:000000}", item.jobId)
            </td>
            <td>@item.jobName
            </td>
        </tr>
    }
</table>

Any help would be appreciated.


Solution

  • It's difficult to understand your problem from the question - 'I don't know what to do' is a bit vague.

    However, this is my guess to your problem:

    If the elemental result (i.e. IEnumerable of element) of that query is an anonymous type due to a select new {}, then I suggest making a known type which mirrors the results you expect (all the way through, incidentally - i.e. nested enumerables etc) and replace the anonymous projection with that type instead. Now you can use that type declaratively in the view.

    i.e. if your query is like this

    from job in jobs
    where !job.deleted
    select new { id = job.id }
    

    Make yourself a model type:

    public class JobQueryResult{
      public int id { get; set; }
    }
    

    And change your select accordingly:

    select new JobQueryResult { id = job.id }
    

    Then you can also make a constructor on the model type, which simply takes a Job object, and have that pull in the data you need (taking the responsibility away from the query expression).

    Either way, you now you have an IEnumerable<JobQueryResult> which you can easily use as a Model type in your view.

    A quick and dirty would be to consider using dynamic instead - (but you didn't hear that from me).