ASP.NET MVC: Cannot use a lambda expression as an argument to a dynamically dispatched operation

走远了吗. 提交于 2019-12-23 07:29:12

问题


I have a ASP.NET MVC4 Application. My view get a List from my controller. I want to select these list with lambda expression but I get the following error:

Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type

List<project.Models.LAYER> layers = new List<project.Models.LAYER>();
layers = @Model.layers.Select(x => x.KONT == "EUROPE");

@Model.layers is a List

NOW I TRIED THAT: BUT THE SAME ERROR:

@{
  List<project.Models.LAYER> layers = Model.layers.Where(x => x.KNOT == "EUROPE").ToList();
}

回答1:


It looks like you're doing this in your view, which violates the principles of separation of concerns. But this is how you would do it.

@
{
   var layers = Model.layers.Where(x => x.KONT == "EUROPE").ToList();
}

@foreach(var layer in layers)
{
  .....
}

A Better Way

What you should do however is create a method on your Model "GetLayersForLocation" Then your code would look like this:

In Your Model Class

public IEnumerable<Layer> GetLayersForLocation(string location)
{
    return this.layers.Where(x => x.Knot == location);
}

In Your View Code

@foreach(var layer in Model.GetLayersForLocation("EUROPE"))
{
  .....
}

The reason this is better is you can now unit test your code, before you wouldn't be able to because it's just part of your view, but now you can run automated tests to ensure that getting the proper layers is working.




回答2:


For others, I've notice I get this error in Views when I do not have a strongly typed view, such as if a single character accidentally gets typed before the "@model type" line (and thus the model type declaration is now no longer being made.)

 @model SomeModel



回答3:


  1. layers is a List, Model.layers.Select will return an IEnumerable.

  2. If you only want to return layer whose KONT == ‘EUROPE', you should use like following

    layers = @Model.layers.Where(x => x.KNOT == "EUROPE").ToList();
    


来源:https://stackoverflow.com/questions/17083616/asp-net-mvc-cannot-use-a-lambda-expression-as-an-argument-to-a-dynamically-disp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!