Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert message from C#

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

like image 644
Neelam Prajapati Avatar asked Jun 27 '16 08:06

Neelam Prajapati


2 Answers

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>
}
like image 64
Anders Marzi Tornblad Avatar answered Sep 28 '22 13:09

Anders Marzi Tornblad


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.

like image 37
Rahul Nikate Avatar answered Sep 28 '22 13:09

Rahul Nikate