ASP.NET 5 Complex TagHelper - asp.net-core

Is it possible to build complex taghelper in ASP.NET 5 where the custom tag have child elements/tags of a certain type?
<blockSection columns="2" labelPosition="left">
<inputField for="name" />
<inputField for="email" required="true"/>
</blockSection>
The in the above example, the blockSection will be a TagHelper that only accepts inputField tags.

Without a whole bunch of trickery (parsing a tags body yourself or creating a TagHelper that targets everything) you can't do this 100% today (beta6).
You can partially fix your issue by ensuring <inputField> elements only appear inside of a <blockSection> tag (would not restrict you from putting things like <p> inside of a <blockSection>). Can be accomplished by using context.Items bag to notify an InputFieldTagHelper that it's (or is not) encapsulated by a <blockSection>. See this issue for information on how to communicate between child => parent.
If you're willing to wait for this Razor issue to be completed; you'll be able to enforce what tags can appear inside your TagHelper.
Another similar SO issue for reference.

Related

How to make a custom element post its value during form submit?

I'm creating a custom element that wraps a third-party control. For some reason, I have to apply this 3rd-party control on a <div> instead on an <input> or else it will behave differently.
I'm using x-tag to create the custom element.
You could insert a <input> tag with attribute type="hidden" and then duplicate the content of the <div> you want to post, it should work.
As an example, you can read this other post on SO.

Rendering an aurelia custom element in ag-grid header

Is there an "easy" way to render a custom element in ag-grid header cell? The headercomponent interface seems like an overly cumbersome approach to a seemingly simple problem and I have not been successful with this approach. The closest I have come is to use something like:
header-cell-render.bind="myHeaderRenderer"
which is currently a function returning a string of HTML. While this "works" (though I understand it is deprecated), in the sense that the html is injected into the DOM, only primitive HTML renders. Meaning I can return something like:
<input type="checkbox" />
and it will render a checkbox, but I cannot return something like:
<my-custom-element></my-custom-element>
I can see that markup in the DOM, but the element doesn't "process", that is the Aurelia aspect of the control is not executed.
I am using the latest versions of ag-grid, ag-grid-aurelia.
Any help would be greatly appreciated.
This is currently not possible out of the box with ag-grid-aurelia.
This is because ag-grid-aurelia makes no special handling for this binding. The proper way to handle this is using replaceable parts which allows you to specify a template for Aurelia to inject and consume. ag-grid makes this a bit harder since it seems the only native tool for injecting content into the header is by passing an HTML string or an HTML element in the column configuration. This can likely be added to the ag-grid-aurelia library by using a combination of replaceable parts and the #children decorator to gain access to the aurelia-rendered header element and pass it to the column configuration.

What is the advantage of using Tag Helpers in ASP.NET Core MVC

I just come across a good write up for a new ASP.NET Core feature called Tag helpers.
From there, I understood that one can replace the following code:
#model MyProject.Models.Product
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(m => p.Name, "Name:")
#Html.TextBoxFor(m => p.Name)
</div>
<input type="submit" value="Create" />
}
with:
#model MyProject.Models.Product
#addtaghelper "Microsoft.AspNet.Mvc.TagHelpers"
<form asp-controller="Products" asp-action="Create" method="post">
<div>
<label asp-for="Name">Name:</label>
<input asp-for="Name" />
</div>
<input type="submit" value="Save" />
</form>
There's some new syntax such as asp-controller, asp-for, etc. But what does it do? And what's the advantage of this new approach?
The most important improvement I've seen so far is the control it guarantees over your HTML elements. While convenient, the Html helpers used by MVC create problems when you try to do things they weren't built for.
A simple example can be seen when using the TextBox in MVC5:
#Html.TextBoxFor(m => p.Name)
The resulting HTML markup looks like:
<input class="form-control" id="Name" name="Name" type="text" value="">
Nice and simple. But what if you want to add a placeholder attribute? What if you want to use bootstrap's validation states? What if you have some 3rd party super cool javascript library which needs custom attributes. None of these things were possible in the initial release of MVC5. Though they were eventually added via update in the form of htmlAttributes. Even now adding custom attributes is kludgey at best.
#Html.TextBoxFor(m => p.Name,
new {#class="form-control has-error", placeholder="Enter Name",
superCoolFeature="Do something cool"})
While you could argue this is still less code that straight HTML, it is no longer a significant advantage. Worse, this solution still doesn't cover dashes in attributes which are fairly common. If you need them you are stuck with a workaround such as ActionLink htmlAttributes
I've gone down the route of fixing these deficiencies with custom editors, and tried building my own TextBox controls. It became obvious pretty quickly that replacing the included TextBox templates would require a lot of work. Worse, your templates have to have knowledge of any extensions you are adding to use them.
It seems like the inclusion of Bootstrap and other 3rd party tools into MVC have made it more obvious that the current design has problems with extending HTML which need to be fixed. Hopefully the tag helpers implementation is complete enough that we can avoid them in the future.
Not to mention, your Web Designers will have real HTML tags to edit that they recognize to re-design your pages. Designers shouldn't have to be coders and there's enough for these sharp folks to keep up with, studying the moving targets of HTML5 and CSS3 specs.
A few things come to mind:
As #ChrisWalter points out, these tag helpers give HTML tags an Open/Closed quality. Rather than just letting you write extension methods for common HTML patterns, you can extend an HTML element. This lets you pick-and-mix multiple extensions per component, rather than having to choose between them.
HTML Helpers tend to not work super well for elements that need to have inner HTML provided as an argument. They came up with a clever pattern so you can say:
#using (Html.BeginForm(...)){
{
<input ... />
}
But there's nothing about BeginForm() that would force you to put it in a using statement, and there's nothing to prevent you from using incorrect HTML structure. (<input> technically isn't allowed to be directly inside a <form> tag.)
This gives us a really easy transitional stepping stone into the Web Components world of HTML5. A component that you write today for jQuery or Bootstrap to pick up and enhance may make more sense as an Angular 2 or Polymer component in a few years. Using HTML syntax makes it possible to write your HTML the way you want it to look when it's a web component, and have it automatically translated into the structure it has to take on for now (or for specific browsers, later).
Accepted answer is correct but just a correction.
Html Helpers cover dashes in attributes by use of underscore. for example if you want html like
my-attr=value
then you can use html helpers like
#Html.TextBoxFor(m=>m.id,
new { my_attr = value })
then it will convert accordingly.
I know the original question asks about advantages but for the sake of completeness I have to mention one disadvantage:
With tag-helpers enabled you cannot inject C# code inside tag attributes.
I.e. this code will break:
<!-- this won't work -->
<input class="#GetMyClass()">
<!-- this won't work too -->
<input type="checkbox" #(condition ? "checked" : "") >
To work around this problem you can use custom tag helpers or just disable tag helpers altogether like described in this answer: https://stackoverflow.com/a/65281018/56621
P.S. My humble opinion that can be safely ignored: tag helpers are "magic". And "magic" is always bad in programming. If something looks like an HTML tag, walks like a tag and quacks like a tag - then it should probably be an HTML tag. Without me knowning "oh, it's not *really* a tag".
From building a basic web app from the ground up in .NET 7/Razor pages, I haven't encountered a single instance where a tag helper has an advantage over simply coding the HTML. I don't come from an MVC background so maybe that is where the advantage lies but as seen before...Microsoft has released yet another version of wheel-reinvention that instead of making things easier for some simply adds more confusion to others.

Using TagHelpers vs ViewComponents in ASP.NET MVC6

I'm trying to understand the use case differences between TagHelpers and ViewComponents in asp.net 5 because the end result functionality seems very similar. We have TagHelpers that can create new HTML tags that get parsed by the Razor engine and then ViewComponents that get explicitly invoked. Both return some HTML content, both are backed by their respective base classes, both have async versions of methods they can implement to get their work done.
So when would one be used over another? Or am I missing some information?
There's definitely some conceptual overlap between TagHelpers and ViewComponents. TagHelpers are your utility to work with HTML where ViewComponents are your way to stick to C#, do isolated work and then spit out HTML. I'll go into each in detail:
ViewComponents
Your conceptually equivalent mini-controller; you will see that many of the methods/properties that ViewComponents expose are very familiar to those that exist on a Controller. Now as for invoking ViewComponents, that's more equivalent to utilizing HTML helpers (one thing TagHelpers make better). To sum up ViewComponents: Their primary purpose is to feel like a controller, stay in C# land (there may be no need to add utility to HTML), do smaller/isolated work and then spit out stringified HTML.
TagHelpers
A utility that enables you to work along side existing HTML or create new HTML elements that modify what happens on a page. Unlike ViewComponents TagHelpers can target any existing HTML and modify its behavior; example: you could add a conditional attribute to all HTML elements that would conditionally render the element server side. TagHelpers also allow you to intermingle common HTML terms, ex:
<myTagHelper class="btn">Some Content</myTagHElper>
As you can see we're adding a class attribute to our TagHelper just as if it were HTML. To do this in ViewComponents, you'd need to pass in a dictionary of attributes or something equivalent (unnatural). Lastly multiple TagHelpers can run over a single HTML element; each having their own stage at modifying output (allows entry for modular TagHelper toolkits). To sum TagHelpers up: They can do anything that ViewComponents can do and more BUT do not feel familiar to things like Controllers that ASP.NET developers are used to; also some projects may not want to intermingle server side HTML.
Extra:
I recently did a video showcasing the benefits of TagHelpers. Basically a walk through of what they're good at and how to use them. You can watch it here.
When deciding which one to use I always consider how complex the HTML of the component will be.
If it's something simple like a tree view or a pager
<ul class="jstree">
<li>Node 1</li>
<li>...</li>
</ul>
That is candidate for tag helper, because it's simple. Large HTML in a C# code would be hard to maintain.
On the other hand if it's complex HTML with many divs, images and configuration like a full blown menu where it can be vertical or horizontal that's your view component. Benefit of view component is that you can use multiple views so for menu so you can separate horizontal.cshtml & vertical.cshtml while reusing same backend code.
Turns out that in .Net Core 1.1, you can call a ViewComponent using the tagHelper syntax.
Regarding Taylor's comment "Their primary purpose is to feel like a controller", it is true, but since you cannot directly call this "micro-controller" directly, the "controller-like" behavior is limited in that you can only create a part of a page, you cannot call it again (say via an ajax call, an Edit Action, etc).
One primary difference between TagHelpers and ViewComponents relates to how much work needs to be done by the object. TagHelpers are fairly basic, requiring only a single class that overrides the Process method to produce the output of the TagHelper. The downside is that if you do any complex work to create inner HTML in the TagHelper, it has to all be done in code. In a ViewComponent, you have a mini-controller capable of doing a lot more work, plus it returns a view, where you have actual Razor syntax code that can be mapped to a model.
Another post mentioned that ViewComponents are more "HTML Helper"-y in how you call them. ASP.NET 1.1 addressed that issue, so that you can call it with
<vc:view-component-name param1="value1" param2="value2></vc:view-component-name>
For most purposes, a TagHelper has a definite advantage, because it's easier. But if you need a more robust solution, ViewComponent is the way to go.
And yet something that kind of defeats the purpose of View Components (IMHO) is that from the View Component class there seems to be no way to access the Inner Html of the VC if you use the tag helper syntax:
<vc:MyComponent id="1" att="something">
Some HTML markup you would not want to put in an attribute
</vc:MyComponent>
There are however good applications of a VC such as the Bootstrap Navigation Bar View Component I saw in a TechieJourney blog post.

Remove <div> generated around Shared Block in EPiServer 7

Episerver always wrap shared block in a tag. I would like to get rid of this. So if in my LinkBlock has a Template with only
link
I would not get a
<div>link</div>
in the view for a user.
If this is not possible how can I change <div> to any other tag, or put a CssClass on it. Like it is possible in not shared blocks:
<EPiServer:Property runat="server" PropertyName="RightContentArea" CustomTagName="aside" CssClass="column-2 sidebar"></EPiServer:Property>
I believe it is the rendering of the ContentArea property which adds the div tags around the blocks it contains.
EPiServer suggests that in order to preserve the editing functionality of the block elements themselves they need to have the div around them.
A possible solution might be for you to do your own custom rendering of content areas, but depending on the kind of block templates you're using it can be tricky to get editing to work. The example in the link is for rendering multiple blocks of the same type.
You can use the CustomTagName and CssClass properties of the Property control to format the container element.
You may also use RenderSettings to modify container elements of child elements (where applicable).
I use this trick in cshtml:
#RenderBlocks(Model.CurrentPage.Content1)
#* ---------------------------------------------------------------------------------- *#
#* Render ContentArea without addition DIVs that EpiServer embed. That breaks layout a lot. *#
#helper RenderBlocks(EPiServer.Core.ContentArea content) {
if(null != content){
var blocks = content.FilteredContents.ToArray();
foreach(var block in blocks){
#Html.PropertyFor(x => block)
}
}
}
You can choose the tag using the CustomTagName attribute on the Property Control
Alternatively, if you wanted to remove the tag, you could use a control adapter. A good example is found here
You can also create a custom content area that doesn't render the divs when edited in live mode and only renders them in edit mode.
If you only need to do this once or twice I would still recommend going with the ChildrenCustomTagName route as it's a bit mroe flexible. If you need to do this a lot and you can't change your CSS easily then I would go custom content area. If you are interested in how to remove the div's I wrote a blog post and a sample site on github here Extra divs in content area how to remove them ?
Since i wasn't able to remove the <div>'s i didn't want, i put my own CSS class on them. This did the trick for me in Webforms. (If anyone still uses it)
Use <RenderSettings ChildrenCssClass="yourCssClass" />
<EPiServer:Property runat="server" PropertyName="RightContentArea"CustomTagName="aside" CssClass="column-2 sidebar"><RenderSettings ChildrenCssClass="yourCssClass"></RenderSettings></EPiServer:Property>