【问题标题】:Adding html elements to page with MVC Razor pages使用 MVC Razor 页面向页面添加 html 元素
【发布时间】:2020-10-02 23:50:55
【问题描述】:

在我的页面的 html 中,我有一个 <script id="pagedata"></script> 元素,我想仅在呈现某个部分时添加一个元素。在我的 layout.cshtml 中,我有以下内容:

@if (Brand != null)
{
    @Html.Partial("_UseApp");
}

在我的 _UseApp.cshtml 中:

@{

    var iosAppUrl = // retrieve iosLink from our CRM database
    var androidUrl = // retrieve android link from our CRM database 

    // Here I want to add the above variables to the <script id=pagedata> in the html page. Something 
    like this: 

    PageData.AddPageData("appstore", iosAppUrl);
    PageData.AddPageData("playstore", androidUrl);

我不知道如何执行此操作 - 我在 UseApp.cshtml 文件中设置断点并且正在调用该文件,但我不知道如何添加这些脚本元素。我不想只是将它们添加到布局文件中,因为我想将应用程序逻辑分开。任何人都可以帮忙吗?谢谢

【问题讨论】:

  • @JacobHallgarth 谢谢 - 但是在这些脚本标签之间放什么?
  • 您能否详细说明您想要实现的目标?从您的问题中,我了解到您想要执行 JavaScript 代码,只有在呈现部分视图的情况下。对吗?
  • 不,@JacobHallgarth,我只想在呈现部分视图时向页面的 HTML 添加元素
  • 所以你想在呈现某个部分时向页面添加 HTML 元素?或者,您想为&lt;script&gt;&lt;/script&gt; 标签添加一个属性?
  • 渲染 UseApp 部分时,我想向已经存在的&lt;script id="pagedata"&gt;&lt;/script&gt; 页面元素添加一个属性。所以它最终是:&lt;script data-playstore="link" id="pagedata"&gt;&lt;/script&gt; 而不是 @JacobHallgarth

标签: html asp.net-mvc razor razor-pages


【解决方案1】:

我的方法是使用 jQuery,因为在 C# 中读取 HTML 元素相当困难。

在下面的脚本中,它检查 HTML 是否存在,如果存在,我们将为其分配一个属性。 attr() 中的第二个参数将是您的链接,请注意,您可以使用 C# 通过模型或 ViewBag 从您的 Db 中获取值。

@section Scripts{
    <script>
        $(document).ready(function () { // on ready
            if ($("#replaceWithYourId").length) { // check if ID exists
                $("#pagedata").attr("data-playstore", "link") // use jQuery attr method.
            }
        });
    </script>
}

【讨论】:

  • 谢谢@JacobHallgarth - 我的问题是在页面上获得data-playstore 属性 - 目前它甚至没有被添加。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2012-06-20
  • 1970-01-01
相关资源
最近更新 更多