简体   繁体   中英

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

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

Strongly typed views are the preferred method. You can also pass data to the view through the Viewbag object, and reference the Viewbag in the view itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM