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

后端 未结 4 1093
轻奢々
轻奢々 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:03

    In all cases the TModel will be the same (the model declared for the view), and in my case, the TValue was going to be the same, so I was able to declare the Expression argument type:

    @helper FormRow(Expression> expression) {
      
    @(Html.LabelFor(expression, new { @class = "control-label col-sm-6 text-right" }))
    @Html.EnumDropDownListFor(expression, new { @class = "form-control" })
    @Html.ValidationMessageFor(expression)
    }

    If your model fields are all string, then you can replace MyClass with string.

    It might not be bad to define two or three helpers with the TValue defined, but if you have any more that would generate some ugly code, I didn't really find a good solution. I tried wrapping the @helper from a function I put inside the @functions {} block, but I never got it to work down that path.

提交回复
热议问题