【问题标题】:Alert message from C#来自 C# 的警报消息
【发布时间】:2016-10-29 04:03:23
【问题描述】:

有没有其他方法可以在 asp.net web 应用程序中显示来自后端的警报消息而不是这个。

ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage","alert('Called from code-behind directly!');", true);

我也包含了 using System.Web.UI 命名空间,但这段代码仍然出现以下 2 个错误:

第一个错误:

最好的重载方法匹配 'System.Web.UI.ScriptManager.RegisterStartupScript(System.Web.UI.Page, System.Type, string, string, bool)' 有一些无效 参数 D:\my_backup\Demos\NewShop\NewShop\API\ProductAPIController.cs 85 17 新店

第二个错误:

参数 1:无法从 'NewShop.API.ProductAPIController' 转换为 'System.Web.UI.Page' D:\my_backup\Demos\NewShop\NewShop\API\ProductAPIController‌​.cs 85 53 新店

【问题讨论】:

  • 这有什么问题?
  • 这段代码有什么错误?什么没有按预期工作?您收到任何错误消息吗?
  • @up-voter :我认为这个问题不值得 +1
  • Response.Write("<script>alert('another way to display the alert message');</script>");

标签: c# asp.net asp.net-mvc code-behind scriptmanager


【解决方案1】:

错误消息告诉您出了什么问题。 RegisterStartupScript 方法需要System.Web.UI.Page 类型的第一个参数,它在 ASP.NET WebForms 中使用。相反,您将 this 作为第一个参数传递,这是一个 Controller 类,用于 ASP.NET MVC!

这意味着您使用的代码适用于另一种 Web 架构。要控制 Controller 的 JavaScript 输出,最好使用 ModelViewBag。像这样:

在您的控制器代码中

ViewBag.ShowAlert = true;

在你看来

@if (ViewBag.ShowAlert)
{
    <script>alert("(Almost) called from code-behind");</script>
}

如果您需要完全控制所呈现的脚本,请将脚本保存为 ViewBag 中的字符串,尽管绝对不推荐这样做!

在您的控制器代码中

ViewBag.SomeScript = "alert('Added by the controller');";

在你看来

@if (ViewBag.SomeScript != null)
{
    <script>@Html.Raw(ViewBag.SomeScript)</script>
}

【讨论】:

    【解决方案2】:

    如果您正在寻找其他方式,那么这里就是

    Response.Write("<script>alert('Called from code-behind directly!');</script>");
    

    注意:但这不是好方法。你永远不会知道你的代码将被插入到哪里。它也可能会破坏 HTML 并导致Javascript 错误。 RegisterClientScriptBlock 是对的 在客户端运行Javascript 的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2014-02-27
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多