1

Want to add an alert box like stackoverflow. i saw some good examples but not something i want. I want different messages that are appearing on different occasions.

ex. I want this msg from C# code when user logins. Also when user places an order. or something is wrong.

This answer is good but the message is appearing on page load. Another example demonstrate the same.

Community
  • 1
  • 1
syed mohsin
  • 2,948
  • 2
  • 23
  • 47

3 Answers3

1

If you don't want to do it on page load but you want it to be driven by code behind (C#) you'll need to use AJAX.

Using JQuery this is easily accomplished by doing something like the following (this is my generic 'perform this action on this controller' in ASP.NET MVC):

 <script type="text/javascript">
 function execute(controller, action) {
        $.ajax({
            type: 'get',
            url: ('/' + controller + '/' + action),
            dataType: 'text'
        }).done(function (data, textStatus, jqXHR) {
            $('#response').html(data).slideDown();
        }).fail(function (jqXHR, textStatus, errorThrown) {
            $('#response').html(jqXHR.responseText).slideDown();
        });
    }
 </script>

You can expand this out to pass whatever data you need to whatever URL you need such as:

 <script type="text/javascript">
 function execute(controller, action, username, password) {
        $.ajax({
            type: 'get',
            url: ('/' + controller + '/' + action),
            dataType: 'text',
            data: ('username='+username+'&password='+password)
        }).done(function (data, textStatus, jqXHR) {
            $('#response').html(data).slideDown();
        }).fail(function (jqXHR, textStatus, errorThrown) {
            $('#response').html(jqXHR.responseText).slideDown();
        });
    }
 </script>

On the server side you just return the string of what you want the response to say, such as "Success! You've been logged in!" and then the element id'ed "response" will have its inner HTML swapped out with that response, and then will be slid open:

 <div id="response" style="display:none"></div>

Be aware that the .fail() event will push out the entire error page you would throw if you don't just return a string on a thrown exception. .fail() will trigger if the HTTP status code from the server is not 200 (OK).

If you're using ASP.NET MVC your C# code can look like this:

 namespace MySite.Controllers
 {
     public class SomeController : Controller
     {
          public string Login(string username, string password){
               // Process login
               return "You've been logged in!";
          }
     }
 }

If you're using Webforms:

 //On Page_Load() call a function if it's an AJAX Login
 // such as 
 if(Request["ajax"] == "login"){
       AjaxLogin(Request["username"], Request["password"]);
 }

 private void AjaxLogin(string username, string password){
      // Process login
      Response.Write("Ajax login complete!");
      Response.End(); // Don't send anything else and stop processing request.
 }

Then to call it simply pass the variables to your function:

 <a onclick="execute('MyController', 'Login', 'UserName', 'MyPass')">Login!</a>

Obviously this assume you have the data you need to process a login request before they enter it, which would be a little self defeating so you can extend out a specific function using JQuery to grab form element content such as:

 <input type="text" name="username" id="username" />
 <input type="text" name="password" id="password" />

Then in your function add:

 <script type="text/javascript">
 function login(controller, action) {

      var username = document.getElementById('username').value;
      var password = document.getElementById('password').value;

        $.ajax({
            type: 'get',
            url: ('/' + controller + '/' + action),
            dataType: 'text',
            data: ('username='+username+'&password='+password)
        }).done(function (data, textStatus, jqXHR) {
            $('#response').html(data).slideDown();
        }).fail(function (jqXHR, textStatus, errorThrown) {
            $('#response').html(jqXHR.responseText).slideDown();
        });
    }
 </script>
siva.k
  • 1,344
  • 14
  • 24
  • Very good detailed answer. i m not using MVC So can i use it in ASP.NET webforms? – syed mohsin Mar 31 '13 at 08:22
  • Added a code example for Webforms. Inside the Page_Load function you'll need to intercept if it's an AJAX login, just add an extra variable to the data line in the Ajax call with a switch flag for yourself, and then checking for that and calling the right function. Then just change the Ajax request URL to in the JS to point to that page URL. – siva.k Apr 01 '13 at 17:40
  • Additionally this is wildly un-secure code, I wouldn't put this into production, you should be doing request validation and all of that also. – siva.k Apr 01 '13 at 17:41
1

You need to create a generic-http-handler or web service or page-method and call it through jQuery and show the message on the alert.

create a handler like this

  public class VideoViewValidation : IHttpHandler
  {
      public void ProcessRequest(HttpContext context)
      {
           string videoID = string.Empty;
           string id = context.Request["Id"];
           context.Response.Writ("your message");
      }
}

and call it through jQuery on button client click

$.ajax({
        url: 'VideoViewValidation.ashx',
         type: 'POST',
          data: { 'Id': '10000', 'Type': 'Employee' },
          contentType: 'application/json;charset=utf-8',
          success: function (data) {
                    alert('Server Method is called successfully.' + data.d);
                },
          error: function (errorText) {
                alert('Server Method is not called due to ' + errorText);
          }
       });
शेखर
  • 17,412
  • 13
  • 61
  • 117
  • I am not familiar with `generic-http-handler`. I am working in ASP.Net webforms. Is it applicable there? – syed mohsin Apr 02 '13 at 04:00
  • yes absolutely it's like a page without the designer page. [Here is a good example](http://encosia.com/use-asp-nets-httphandler-to-bridge-the-cross-domain-gap/) – शेखर Apr 02 '13 at 04:17
0

try this

public void message(string msg)
{
    ScriptManager.RegisterClientScriptBlock(this, GetType(), "Done", "alert('" + msg + "');", true);
}

to use this method

write message("You are logged in sucessfully.");

Aijaz Chauhan
  • 1,511
  • 3
  • 25
  • 53