来自C#的警报消息

时间:2016-06-27 08:14:44

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

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

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

我还包括使用System.Web.UI命名空间,但仍然使用此代码获得这两个错误:

第一个错误:

  

最佳重载方法匹配   “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 N ewShop

第二个错误:

  

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

2 个答案:

答案 0 :(得分:3)

错误消息告诉您出了什么问题。 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>
}

答案 1 :(得分:2)

如果您正在寻找其他方式,那么

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

注意:然而,这不是好方法。您永远不会知道代码的插入位置。它也可能破坏HTML   并导致Javascript错误。 RegisterClientScriptBlock是对的   在客户端上运行Javascript的方法。

相关问题