1

Why I can't pass a parameter of type Func<MyModel,bool> from Html.Action to my Controller? When I'm trying the following code it gives me error like this:

public PartialViewResult MyMethod(Func<MyModel,bool> lambda)
{
}

And in Razor:

@{var result = Html.Action("MyMethod", "MyController" , new { lambda = c => !c.Checked});}

The error:

Cannot assign lambda expression to anonymous type property

And this is not a duplicate question because that question is looking for why this happens but I'm looking for a solution.

  • Possible duplicate of [Why can't c# use inline anonymous lambdas or delegates?](https://stackoverflow.com/questions/2687942/why-cant-c-sharp-use-inline-anonymous-lambdas-or-delegates) – Kolichikov Aug 09 '17 at 16:33
  • Because `Html.Action` determines the actual method (`MyMethod` in your case) dynamically and doesn't have any compile-time information about your method. Hence, it has no way to infer the actual type of your lambda expression – haim770 Aug 09 '17 at 16:33
  • @Kolichikov That question is looking for why this happens but I'm looking for a solution. –  Aug 09 '17 at 16:34
  • @haim770 Well if I send it as string then how can I convert the string to the func? What can I do? –  Aug 09 '17 at 16:37
  • 1
    Have you tried casting it? `@{var result = Html.Action("MyMethod", "MyController" , new { lambda = (Func)(c => !c.Checked)});}`. – Kolichikov Aug 09 '17 at 16:38
  • @SteveCode the linked dupe tells you how to solve the problem (as does the previous comment), what makes you think it's not useful? – DavidG Aug 09 '17 at 16:47
  • Wouldn't `lambda = (MyModel c) => !c.Checked` be sufficient? – NetMage Aug 09 '17 at 18:20

1 Answers1

0
@{ var result = Html.Action("MyMethod", "MyController", new { lambda = new Func<Model,bool>( c => !c.Checked) }); }

You can assign new Func<Model,bool> type object with passing lambda in its constructor. Assign lambda or anonymous method to anonymous property is not allowed since from lambda or anonymous method we cannot explictly infer type of delegate.

Pankaj
  • 244
  • 2
  • 4