简体   繁体   English

如何在MVC 4的局部视图中访问动态linq查询的结果(PredicateBuilder linq到实体)?

[英]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. 我有一个控制器操作,该操作使用PredicateBuilder构建动态linq查询。 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? 如果将列表传递给的视图不是强类型的,如何访问视图中的results

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: 或者更常规地使用控制器中的Viewbag动态对象并查看以传递数据:

http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx 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. 您还可以通过Viewbag对象将数据传递到视图,并在视图本身中引用Viewbag。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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