This is for asp.net core 2.1+
If I understand your question correctly, you can replace all your HtmlHelper partial views with your own TagHelpers, but you were already able to do this with HtmlHelpers so its not something new.
However, there is a difference between HtmlHelpers
, TagHelpers
and Partial Views.
Partial Views
A partial view is a Razor markup file (.cshtml) that renders HTML output within another markup file's rendered output. Eg _partial.cshtml
.
HtmlHelper
HtmlHelpers were introduced with the MVC framework to be able to render html serverside. Easily distinguished by the @
character in razor views.
@await Html.PartialAsync("_partial.cshtml", Model.Contact)
Beyond that, TagHelper can accept input but PartialView don't.
The second parameter in PartialAsync
allows for input.
TagHelper
With asp.net-core, TagHelpers are another way to be able to render server side html by using tags and attributes in the razor views. Aside from html friendly views, it provides less abstraction from html. In the code below I'm using the Partial TagHelper, where the name attribute defines the path or name of the view, and the for attribute assigns the model expression that will evaluated (@Model). This means you don't need to use for="@Model.Contact"
and simply just for="Contact"
.
<partial name="_partial" for="Contact" />
You could also use the model attribute, which just passes the model to the partial view on instantiation.
<partial name="_partial" model='new Contact { Id = 1, Name = "Nick" }' />
As seen from above, both TagHelpers and HtmlHelpers can render partial views.
Furthermore if you look at asp.net-core github for the HtmlHelper
https://github.com/aspnet/Mvc/blob/b18526cdc8d8c868e8d7f9c6c8484064215e1002/src/Microsoft.AspNetCore.Mvc.ViewFeatures/HtmlHelper.cs#L554
and compare it to the TagHelper
https://github.com/aspnet/Mvc/blob/b18526cdc8d8c868e8d7f9c6c8484064215e1002/src/Microsoft.AspNetCore.Mvc.TagHelpers/PartialTagHelper.cs#L216
Both are actually calling and IView.RenderAsync()
and passing in a ViewContext
which includes the partial view. So they virtually do the same thing in code behind, except for the way it manipulates the html.
Side notes:
- Much like HtmlHelpers, you can also create your own TagHelpers which can replace whole partial views.
- TagHelpers are not to replace HtmlHelpers, but provide alternative approach. However, in my opinion TagHelpers are better. They render better in visual studio editor (razor pages used have a lot of formatting problems due to the @HtmlHelpers), is way more readable, and comply with html.
- In the partial
TagHelper
, you can use either model
or for
to provide data to the partial, but never both.
- Omitting .cshtml from the name will just force the framework to search for the view in Pages, Views, and Shared folders. Its totally optional.
Hope this helps