【问题标题】:Razor class library and html helpers problemRazor 类库和 html 助手问题
【发布时间】:2019-09-04 10:20:24
【问题描述】:

我创建了一个小型管理工具,并决定将其转换为 Razor 类库,这样我也可以在其他应用程序中使用它。我创建了 Razor 类库项目,并添加了我在主项目中拥有的所有 razor 页面,并尝试测试新项目。问题是框​​架由于某种原因无法识别 html 帮助程序,所以我创建了一个新的干净项目并尝试找出问题所在,结果是应用程序没有触发剃须刀页面和 asp 的 post 操作-for 属性没有正确使用属性值。我使用以下代码来测试 Razor 类库。

Page1.cshtml.cs

public class Page1Model : PageModel
{
    [BindProperty]
    public Input MyInput { get; set; }

    public class Input
    {
        public string Name { get; set; }
    }
    public void OnGet()
    {

    }

    public void OnPost()
    {

    }
}

Page1.cshtml

@page
@model WebApplication1.MyFeature.Pages.Page1Model

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Page1</title>
</head>
<body>
    <form method="post">
        <input asp-for="MyInput.Name" /><br />
        <input type="submit" />
    </form>
</body>
</html>

生成的html如下

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Page1</title>
</head>
<body>
    <form method="post">
        <input asp-for="MyInput.Name" /><br />
        <input type="submit" />
    </form>
</body>
</html>

正如您所见,MyInput.Name 的输入出现在我键入 Page1.cshtml 文件时。正确的输出应该如下:

<input type="text" id="MyInput_Name" name="MyInput.Name" value="" /><br />

我是否必须做一些事情才能使 html 助手工作并在发布请求发生时调用 OnPost 操作?

【问题讨论】:

    标签: asp.net-core asp.net-core-2.0 asp.net-core-2.1 asp.net-core-2.2 razor-class-library


    【解决方案1】:

    我找到了问题的解决方案,我决定与你分享,以防其他人遇到同样的问题。

    为了使它工作,我必须在 Razor 类库的 pages 文件夹中添加文件 _ViewImports.cshtml 并添加以下行:

    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      相关资源
      最近更新 更多