So far, i don't think ViewComponent
solves that neither does TagHelper
. Is there any replacement to this? Something that takes parameters and returns a HtmlString
?
I don't see anything harmful with:
@helper foo(string something) {
<div>Say @something</div>
}
var emailbody = classfilenameinAppCodefolder.foo("hello"); //store result in a variable for further processes
For now i believe its a temporary delete before RC. https://github.com/aspnet/Razor/issues/281 and https://github.com/aspnet/Mvc/issues/1130 Well! it better be. I hope someone is working on it. Without @helper
, building large HtmlString
or 'template' would be a serious pain.
Note: Partial View doesn't seem to do the trick. I think it only renders views not return view to variable.
Secondly, what happened to the App_Code folder?
I'd like to expand on @Alexaku's answer and show how I've implemented a helper like function. It's only useful on one specific page but it allows you to execute a piece of razor code multiple times with input parameters. The syntax is not great but I've found it very useful in the absence of razor's @helper function. First declare some kind of Dto that will contain the input parameters into the function.
Then declare the razor function. Note that the displayItem value can be multi-line and also note that you access the Dto variable using the @item.
Then when you want to use the razor template you can call it like the following from anywhere in the page.
The
@helper
directive was removed since it was incomplete and its current design did not fit in the new 'ASP.NET 5 way'. One of the reasons is that helpers should be declared in theApp_Code
folder while ASP.NET 5 has no concept of special folders. Therefore the team decided to temporarily remove the feature.There are plans to bring it back in the future though. See this and this.
You can easily replace that "feature" with a ViewComponent (and a TagHelper if you want). ASP.NET Core is much more friendly to web designers, and the ViewComponents allow you to write HTML without any (weird to most) razor code.
For example:
Create a
SayComponent : ViewComponent
class:Create a View file under
Views/Shared/Say/Default.cshtml
with justAnd call it:
For a better experience, add this to your
_ViewImports.cshtml
file:And then you can use it as a tag helper: