Is it possible to create a generic @helper method with Razor?

后端 未结 4 1069
轻奢々
轻奢々 2020-11-28 03:25

I am trying to write a helper in Razor that looks like the following:

@helper DoSomething(Expression> expr) where T : clas         


        
4条回答
  •  粉色の甜心
    2020-11-28 04:19

    if your main problem is to get name attribute value for binding using lambda expression seems like the @Html.TextBoxFor(x => x.MyPoperty), and if your component having very complex html tags and should be implemented on razor helper, then why don't just create an extension method of HtmlHelper to resolve the binding name:

    namespace System.Web.Mvc
    {
        public static class MyHelpers
        {
            public static string GetNameForBinding
               (this HtmlHelper model, 
                Expression> property)
            {
                return ExpressionHelper.GetExpressionText(property);
            }
        }
    }
    

    your razor helper should be like usual:

    @helper MyComponent(string name)
    {
        
    }
    

    then here you can use it

    @TheHelper.MyComponent(Html.GetNameForBinding(x => x.MyProperty))
    

提交回复
热议问题