Tuesday, April 5, 2011

Adding the results of two queries to ViewData.Model

I have the following code in my controller:

    public ActionResult Details(int id)
    {
        var dataContext = new BuffetSuppliersDBDataContext();
        var supplier = (from m in dataContext.BO_Suppliers 
                        where m.SupplierID == id
                        select m).FirstOrDefault();

        ViewData.Model = supplier;

        return View();
    }

This renders a view which contains the properties returned from the linq to sql query. What I need to do now is add another query which will return x amount of ratings for each supplier, i will then loop through the records in the view and display the ratings.

How can I push the results of my ratings query into the view along with what is already there?

From stackoverflow
  • Your best option would to be create a class that you can pass into your view.

    public class SupplierDetail
    {
        public Supplier { get; set; }
        public SupplierRating { get; set; }
    }
    
    public class SupplierDetailViewData
    {
        public IEnumerable<SupplierDetail> SupplierDetails { get; set; }
    }
    

    Then in your controller action use a join and select a new SupplierDetail class in the LINQ query. After that you can create a strongly-typed view by using the code-behind and changing it to this...

    public partial class Details : ViewPage<SupplierDetailViewData>
    {
    }
    

    After that, in your view -- ViewData.Model will be SupplierDetailViewData. Of course the second part is optional but it does make for better compile-time validation.

    awharrier : Thanks for your help, I have managed to accomplish what I needed.

0 comments:

Post a Comment