开发者

Using lambda to specify property to Helper class from Razor Partial View

开发者 https://www.devze.com 2023-03-31 00:01 出处:网络
I\'m trying to write a EditorTemplate to generically apply CSS classes dependent upon logic provided in a helper passing the model and additional data from the ViewBag:

I'm trying to write a EditorTemplate to generically apply CSS classes dependent upon logic provided in a helper passing the model and additional data from the ViewBag:

@using LSC.DCMP.Web.UI.Helpers
@model String

@ValidationFieldHelper.GetCSSClass(m => Model, @ViewBag.Step) 

This matches to a helper class that currently isn't implemented, but has the following signature:

public static class ValidationFieldHelper
{
    public static object GetCSSClass(Func<object, string> func, object step)
    {
        throw new NotImplementedException();
    }
}

When I try to run the application, it fails compilation with the following error:

"Cannot use a lambda expression as an ar开发者_如何学运维gument to a dynamically dispatched operation without first casting it to a delegate or expression tree type".

I've read that lambda syntax isn't fully supported using Razor templates so I'm unsure how I can implemented this functionality.


The issue is not to do with the lambda, but to do with the dynamic @ViewBag that you are using, which causes that statement to be dynamically dispatched, as mentioned in the error message.

Two other options to what Major Byte has offered:

  1. Cast the dynamic which lets the compiler know what the dynamic will resolve to

    @ValidationFieldHelper.GetCSSClass(m => Model, (object)@ViewBag.Step)
    
  2. Set the dynamic to a variable before using (basically the same deal as above)

    @{ object vstep = ViewBag.Step; }
    @ValidationFieldHelper.GetCSSClass(m => Model, vstep)
    

Both of these throw the correct exception for me.


Would

@ValidationFieldHelper.GetCSSClass((Func<object, string>) (m => Model), @ViewBag.Step)

work for you? It's not the cleanest solution, but I could get it throwing up the NotImplementedException...

0

精彩评论

暂无评论...
验证码 换一张
取 消