【问题标题】:How to change text from in HTML Label from backend如何从后端更改 HTML 标签中的文本
【发布时间】:2022-10-05 11:14:54
【问题描述】:

我开始学习 ASP.NET Core MVC,只是发现工具箱无法访问/禁用/变灰,所以在 html 中我不能使用 <asp:Label/> 标签,而必须使用 <label></label> 标签。

现在我无法从后端更改 HTML 标记 <label></label> 上的字符串。

对于这种情况,我已经在标签内写了runat="server",但仍然发生了一个错误,上面写着:

当前上下文中不存在名称“lblkpj”

这是示例html:

<label class="text-center mb-1 fw-bold" runat="server" id="lblkpj"> </label>

和 C#:

if (tbl.Rows.Count > 0)
{
    lblkpj.text = "Success";
}
else
{
    lblkpj.text = "Failed";
}

我哪里错了?

【问题讨论】:

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


    【解决方案1】:

    使用Razor markup

    您可以通过声明变量来实现 View 中的逻辑。并使用@ 符号。 Razor 将评估表达式并将输出呈现为 HTML。

    并确保您需要将 ViewModel 作为模型对象的 List 从 Controller 返回到 View。

    看法

    @model List<YourModel>
    @{
      string status = Model.Rows.Count > 0 ? "Success" : "Failed";
    }
    
    <label class="text-center mb-1 fw-bold" id="lblkpj">@status</label>
    

    控制器

    public class YourController : Controller
    {
        public IActionResult YourView()
        {
            // Mock data
            List<YourModel> list = new List<YourModel>();
    
            return View(list);
        }
    }
    

    【讨论】:

    • 你好,我可以再问一下,我应该在 <YourModel> 标签上填写什么?
    • YourModel 是您在其中创建类定义以存储对象实例的类。将 YourModel 单词替换为您使用的类的名称。供您阅读,Strongly-typed data (viewmodel)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多