【问题标题】:Send a script to the browser from C# back-end从 C# 后端向浏览器发送脚本
【发布时间】:2016-06-08 12:23:37
【问题描述】:
我有一条提醒,我只想在用户第一次访问网站时向他发送。条件在 c# 中,这就是我使用的代码。它不发送警报。我该怎么办?
if ((string)Session["alert"] == null) {
Response.Write("<script type='text/javascript'>alert('WELCOME to the website!\nEnjoy!')</script>");
Session["alert"] = "done";
}
【问题讨论】:
标签:
javascript
c#
webforms
【解决方案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";
}
【解决方案2】:
试试这个代码。
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";
}
要考虑的是,您的文字项目应添加到正文 html 标记的末尾。
我希望这会有所帮助。