从C#后端向浏览器发送脚本

时间:2016-06-08 12:23:38

标签: javascript c# webforms

我有一个警告,我只想在他第一次进入网站时发送给用户。条件是c#,这是我使用的代码。它没有发送alret。我该怎么办?

if ((string)Session["alert"] == null) {
        Response.Write("<script type='text/javascript'>alert('WELCOME to the website!\nEnjoy!')</script>");
        Session["alert"] = "done";
    }

2 个答案:

答案 0 :(得分:1)

如果您使用的是ASP.NET Web窗体,则可以使用ScriptManager,如下所示:

ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('WELCOME to the website!\nEnjoy!')", true);

如果将最后一个参数设置为true,则内容将包含在脚本标记中。

您的代码如下所示:

if ((string)Session["alert"] == null) {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('WELCOME to the website!\nEnjoy!')", true);
        Session["alert"] = "done";
}

答案 1 :(得分:0)

试试这段代码。

ASPX

    <body>
<form id="form1" runat="server">
<asp:Literal id="ltrMessage" runat="Server"/>
</form>
</body>

ASPX.CS代码

if ((string)Session["alert"] == null) {
    ltrMessage.Text="<script type='text/javascript'>alert('WELCOME to the website!\nEnjoy!')</script>";
    Session["alert"] = "done";
}

要考虑,您的文字项应添加到最终的Body html标记中。 我希望有所帮助。