【问题标题】:What does asp-for do behind the scenes?asp-for 在幕后做了什么?
【发布时间】:2019-07-12 04:50:01
【问题描述】:

我在 .cshtml 文件中有这段代码:

<label asp-for="Email">Your email:</label>

解析后幕后发生了什么?

我可以看到asp-for实际上调用了Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper.For

但是IHtmlGenerator 的什么实现被传入LabelTagHelper 构造函数?

在 .NET 控制台应用程序中,我可以在 ILSpy 中打开 .exe 以查看发生了什么。

我怎样才能为 Asp.net Core 应用程序做同样的事情?

【问题讨论】:

    标签: asp.net-core-mvc asp.net-core-2.2


    【解决方案1】:

    您可以查看 LableTagHelper 源代码:

    https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.TagHelpers/src/LabelTagHelper.cs

    IHtmlGenerator被传入构造函数并生成lable标签

    var tagBuilder = Generator.GenerateLabel(
                ViewContext,
                For.ModelExplorer,
                For.Name,
                labelText: null,
                htmlAttributes: null);
    

    更新:

    默认的 Asp.net Core MVC 尽可能避免直接依赖。而不是硬编码IHtmlGenerator 接口的实现,Asp.net Core MVC 在应用程序初始化过程中加载依赖注入的实现。当视图引擎创建IHtmlHelper的接口时,它通过构造函数传递IHtmlGenerator实例。

    参考here

    【讨论】:

    • 但是需要传入一个IHtmlGenerator的实现,那个实现类是什么?
    • IHtmlGenerator的默认实现是DefaultHtmlGenerator。我挖了一下,找到了,请看我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2019-05-21
    • 2016-03-19
    • 1970-01-01
    • 2010-11-21
    相关资源
    最近更新 更多