I have 2 questions:
1. what is Viewcontext and what are its advantages?
2. why we have to use it in tag helpers?
Actually i am the beginner and follow the "Pro ASP.NET Core MVC,6th Edition" by adam freeman in this he make a taghelper class in which he uses
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; }
He didn't explain the above piece of code why he uses these properties in square brackets purpose of these properties. And please share a link which describe about these type of properties if any
The ViewContext
object is the object that provides access to things like the HttpContext, HttpRequest, HttpResponse and so on. The way that you can gain access to it in a TagHelper is via a property but in such a case you need to set the [ViewContext]
attribute so that the property gets set to the current ViewContext
.
So for example you can gain access to the current request via the following:
var currentRequest = ViewContext.HttpContext.Request;
[HtmlAttributeNotBound]
basically says that this attribute isn't one that you intend to set via a tag helper attribute in the html.
Your tag helper may not need access to the ViewContext
object and all it's subobjects. If not, you can omit the ViewContext property and associated attributes from your TagHelper
. It's certainly not a required property for a TagHelper
and most of my own tag helpers so far have not needed access to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With