Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a Razor construct to a helper method, using Razor's @: operator?

I am trying to pass some Html constructed by using razor's @: operator to a helper method, but I can not figure out how to do this. The compiler states that the Razor expression is a lambda expression, but it does not say, what is this lambda expression like... no clues at all!

If I try to do this:

        @(MyClass.MyMethod(new
            {
                Html = @:<div></div>
            }
        ))

The error is as follows: Cannot assign lambda expression to anonymous type property

If I try this instead, then it states it as being a lambda again:

        @(MyClass.MyMethod(
            @:<div></div>
        ))

If the MyMethod receives a string: i.e. public string MyMethod(string razorConstructedString) , then the compiler says: Cannot convert lambda expression to type 'string' because it is not a delegate type.

The question is: what type should I declare MyMethod, so that it can receive the razor constructed parameter?

Thanks!

like image 852
Miguel Angelo Avatar asked Aug 01 '11 14:08

Miguel Angelo


People also ask

Does ASP.NET MVC use razor?

Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML. It's just that ASP.NET MVC has implemented a view engine that allows us to use Razor inside of an MVC application to produce HTML.

What is @helper in Cshtml?

The HtmlHelper class renders HTML controls in the razor view. It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form.

Which HtmlHelper object method should you use?

We can use this HTML. RadioButton() Helper method using the class to define the HTML elements. This is the loosely typed expansion method function which we can define as input type to select the (<input type="radio" >) element in razor view. We can declare the @Html.

What is razor view in ASP.NET MVC?

Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup.


1 Answers

This is called an inline helper.
It's a Func<AnyType, HelperResult>.

You can call this delegate with a parameter, and the parameter will be accessible in the helper, named item.

like image 108
SLaks Avatar answered Oct 10 '22 08:10

SLaks