How do I access the results of the dynamic linq query (PredicateBuilder linq to entities) in a partial view in MVC 4?

advertisements

I have a controller action that uses PredicateBuilder to build a dynamic linq query. I want to pass the results of this query to a partial view. What is the best way to do this? If it's best practice to always use strongly typed views, should my view model that I pass to the controller action have a list that I can pass the results of the query into? Or is this just extra overhead using two lists?

Here's a simplified version of the controller action:

[HttpPost]
public ActionResult BasicPropertySearch(BasicPropertySearchViewModel viewModel)
{
    var predicate = PredicateBuilder.True<ResidentialProperty>();
    if (ModelState.IsValid)
    {
        using(var db = new LetLordContext())
        {
            predicate = predicate.And(x => x.HasBackGarden);
            predicate = predicate.And(x => x.HasFrontGarden);
            predicate = predicate.And(x => x.HasSecureParking);
            predicate = predicate.And(x => x.IsDisabledFriendly);

            var results = db.ResidentialProperty.AsExpandable().Where(
            predicate).ToList();

            return PartialView("_BasicPropertySearchResultsPartial", results);
        }

    }
    ModelState.AddModelError("", "Something went wrong...");
    return View("_BasicPropertySearchPartial");
}

How do I access results in the view if the view the list is being passed to is not strongly typed?


You should use strongly typed view model whenever is possible, however you can use 'dynamic' model in your partial view to access to your data. Or to be more conventionally use the Viewbag dynamic object in your controller and view to pass data:

http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx