简体   繁体   English

使用 MVC Razor 页面将 html 元素添加到页面

[英]Adding html elements to page with MVC Razor pages

On the html for my page I have a <script id="pagedata"></script> element which I would like to add an element to only if a certain partial is rendered.在我的页面的 html 上,我有一个<script id="pagedata"></script>元素,我想仅在呈现某个部分时才添加一个元素。 In my layout.cshtml I have the following:在我的 layout.cshtml 中,我有以下内容:

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

And in my _UseApp.cshtml:在我的 _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);

I cannot work out how to do this - I set breakpoints in the UseApp.cshtml file and the file is being called, but I don't know how to add these script elements.我无法弄清楚如何执行此操作 - 我在 UseApp.cshtml 文件中设置断点并且正在调用该文件,但我不知道如何添加这些脚本元素。 I don't want to just add them into the layout file because I want to keep the app logic separate.我不想只是将它们添加到布局文件中,因为我想将应用程序逻辑分开。 Can anyone help?任何人都可以帮忙吗? Thanks谢谢

My approach to this would be to use jQuery, as reading HTML elements in C# is rather difficult.我的方法是使用 jQuery,因为读取 C# 中的 HTML 元素相当困难。

In the script below, it checks if the HTML exists, and if it does, we will assign an attribute to it.在下面的脚本中,它检查 HTML 是否存在,如果存在,我们将为其分配一个属性。 The second argument in attr() will be your link, note that you can use C# to get the value from your Db, by using the model or ViewBag. attr()中的第二个参数将是您的链接,请注意,您可以使用 C# 通过使用 model 或 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>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM