简体   繁体   中英

Use webcomponents in existing ASP.NET WebForms application

I have an large existing ASP.NET WebForms application. This application has a masterpage who manager security, navigation, ... Pages developped are in a ContentPlaceHolder.

I would like to develop new pages in JS with web components. To use a web component on a page, it must be imported ( <link rel="import" href="..."> ). This import must be on the <head> part of the page. In my case, the <head> is on the master page. So I have to import all the existing web components in the master page to be able to use them.

It does not sound like a very good idea.

How can I do it otherwise ?

Asp.Net lets you place ContentPlaceHolder in head tag. You can load the web components required by the page instead of loading them all in Master Page.

Master Page

<html>
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="cpHead" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="cpBody" runat="server">

        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

Web Form

<asp:Content ID="Content1" ContentPlaceHolderID="cpHead" runat="server">
    <link rel="import" href="...">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpBody" runat="server">
</asp:Content>

Your HTML will look like

<html>
<head>
    <title></title>
    <link href="..." rel="import">
</head>
<body>
</body>
</html>

You would normally use RegisterClientScriptInclude . This will add the script file to the top of the page, but not in the <head> .

ClientScript.RegisterClientScriptInclude("myScript", "myJavaScriptFile.js");

If you really want it in the <head> you need to use a HtmlGenericControl

HtmlGenericControl genericControl = new HtmlGenericControl("script");
genericControl.Attributes.Add("type", "text/javascript");
genericControl.Attributes.Add("src", "myJavaScriptFile.js");
this.Page.Header.Controls.Add(genericControl);

It does not matter where you place this code (Master, Page, User Control). Aspnet will ensure they end up in the right place client side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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