带有标签的.Net Core 2.1 asp-for无法正常工作

时间:2019-02-22 21:50:32

标签: .net core

使用Visual Studio 2017,.Net Core 2.1,网站

使用此模型

public class TestObj
{
    [DataType(DataType.Text)]
    public string str1 { get; set; }
    [DataType(DataType.Text)]
    public int int1 { get; set; }
    public List<TestObj> TestList { get; set; }
    public TestObj() { }
    public TestObj(string i_str, int i_int)
    {
        this.str1 = i_str;
        this.int1 = i_int;
    }
}

这个控制器:

    [HttpGet]
public IActionResult Test()
{
    TestObj model = new TestObj();
    model.TestList = new List<TestObj>();
    model.TestList.Add(new TestObj("test1", 1));
    model.TestList.Add(new TestObj("test2", 2));
    return View(model);
}

这是cshtml:

<form asp-action="Test" asp-controller="Home">
<ul>
    @for (int i = 0; i < Model.TestList.Count; i++)
    {
        <li><label asp-for="@Model.TestList[i].str1" /></li>
        <li><label asp-for="@Model.TestList[i].int1" /></li>
        <li><input asp-for="@Model.TestList[i].str1" /></li>
        <li><input asp-for="@Model.TestList[i].int1" /></li>
    }
</ul>

我得到输入框,但没有标签。我已经搜索了Web和Stack Overflow,但找不到输入工作时标签失败的原因。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我被卡在这上面了一段时间。标签标签必须由另一个标签关闭,而不是在同一标签内。否则它将无法正常工作。

这将起作用:

<label asp-for="Date" class="col-form-label col-sm-3" />

这将:

<label asp-for="Date" class="col-form-label col-sm-3"></input>

答案 1 :(得分:0)

您必须为此进行一些更改

  1. 正如 SeanTech 所说,你必须用 <label> 括起来 </label> 标签

  2. Tag Helpers 从@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers 导入 它在 ViewImorts.cshtml 中可用。 确保此文件应在您的视图/页面的根级别可用 文件夹。

最重要的是 - 您需要将此行添加到您的 _ViewImports.cshtml 文件中。并且您需要确保特定的 _ViewImports 文件用于您的视图或页面文件夹。

相关问题