Alert message from C#
Asked Answered
U

2

7

Is there any other way to display alert message from back end in asp.net web application rather than this.

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

I have included using System.Web.UI namespace also, but still am getting these 2 errors with this code:

First error:

The best overloaded method match for 'System.Web.UI.ScriptManager.RegisterStartupScript(System.Web.UI.Page, System.Type, string, string, bool)' has some invalid arguments D:\my_backup\Demos\NewShop\NewShop\API\ProductAPIController.cs 85 17 N‌​ewShop

Second error:

Argument 1: cannot convert from 'NewShop.API.ProductAPIController' to 'System.Web.UI.Page' D:\my_backup\Demos\NewShop\NewShop\API\ProductAPIController‌​.cs 85 53 NewShop

Uptown answered 27/6, 2016 at 8:14 Comment(4)
What is wrong with this?Maillol
What error is there with this code? What doesn't work as expected? Do you get any error messages?Preemie
@up-voter : I don't think the question is worth for +1Maillol
Response.Write("<script>alert('another way to display the alert message');</script>");Prase
P
3

The error messages tell you what is wrong. The RegisterStartupScript method requires a first argument of type System.Web.UI.Page, which is used in ASP.NET WebForms. Instead you are passing this as the first argument, which is a Controller class, which is used in ASP.NET MVC!

That means the code you are using is meant for another web architecture. To control JavaScript output from a Controller, you are much better off using the Model or maybe ViewBag. Like this:

In your controller code

ViewBag.ShowAlert = true;

In your view

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

If you need full control over the script that is rendered, save the script as a string in the ViewBag, even though this is definitely not recommended!

In your controller code

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

In your view

@if (ViewBag.SomeScript != null)
{
    <script>@Html.Raw(ViewBag.SomeScript)</script>
}
Preemie answered 27/6, 2016 at 12:9 Comment(0)
P
2

If you are looking for other way then here it is

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

Note : However this is not the good way. You'll never know where your code will be inserted. Also it could potentially break HTML and cause Javascript errors. RegisterClientScriptBlock is right way to run Javascript on client.

Puckett answered 27/6, 2016 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.