Reputation: 2923
I am new to ASP.NET Core. I just discovered TagHelpers and as I may get the idea, theoretically we should be able to replace partial views with tag helpers.
Beyond that, TagHelper
can accept input but PartialView
don't.
do I think right? or it's a misunderstanding? can anyone explain the difference clearly?
Thanks in advance!
Upvotes: 5
Views: 1921
Reputation: 5272
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.
A partial view is a Razor markup file (.cshtml) that renders HTML output within another markup file's rendered output. Eg _partial.cshtml
.
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.
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" }' />
Furthermore if you look at asp.net-core github for the HtmlHelper
and compare it to the TagHelper
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.
TagHelper
, you can use either model
or for
to provide data to the partial, but never both.Hope this helps
Upvotes: 6