Archive for ASP.NET

Some FAQ from ASP.NET web development

Hello! How are you doing? Today, I wanna share with you some of the notes that I have made while I was working in ASP.NET project. I started playing with .NET since September, 2004. I used to face a lot of problems and have to find the solutions for those problems. I wanna share all of those problems and solutions that I’ve faced. But unfortunately, I didn’t remember all of these since I didn’t make any note in my outlook. Anyway, I’ll share with you what I have in my mail. Hopefully, you may find it useful.

1. How to invoke/fire JS function after validating of ASP.NET validator?

Use “Page.RegisterStartupScript(,)” function as below.


        string strScript   = "";
        strScript += "function foo(){";
        strScript += " alert('This is foo!');";
        strScript += "}";
        strScript += "";Page.RegisterStartupScript("bear",strScript);

2. Is it possible to access the Javascript variable from Server-side?

Follow the steps below if you wanna share something between the client-side script and server-side script.

  1. Add Server-side hidden field in your page.
  2. Set the value of Javascript variable to this hidden field by using document.getElementById() function.
  3. then, get the value of that hidden field.

Note: I used this technique in this sample. You may check it out.

3. Why all data from web controls within the disabled panel has been lost during the postback?

It’s pretty strange. In window-based application, we only need to disable the panel if we want to disable all controls inside this panel. But we can’t do like that in web development. ASP.NET doesn’t keep the viewstate of the controls if the panel is disabled so that all data in those controls within disabled panel will be lost during the PoskBack.
The solution for this problem is that enable or disable each and every controls inside the disabled panel. Enable explicitly.

Scott Mitchell wrote very good article about this problem and solution in this blog.. You may check his article “Panel Weirdness” here.

4. How to set the width of textbox in percentage? [esp: for Firefox users.]

This is the problem that I faced when I was developing cross-browser asp.net web application. What happen was that I wanna set the width of a textbox to 100%. So, I set 100% to the width property of textbox in Design Mode. But the style that i set to textbox doesn’t load in Firefox. It automatically change from 100% to 100. I have no idea why it was happening like that. However, I could come up with the solution for that problem. The solution is that write the style you want as a CSS class in CSS file and set it to the textbox.

5. I used to get this error “Access is Denied: Microsoft.Web.UI.Webcontrols”" very often while running asp.net project from VS.NET IDE.Why?

Solution #1 ~

  • Stop Indexing Service.

[ref: http://support.microsoft.com/default.aspx?scid=kb;en-us;329065]

Details ~

If you do not use Index Server on the server, you can disable it. To do so, follow these steps:
1. Click Start, and then click Services.
2. Locate Indexing Service from the list of services, and then click Indexing Service Properties from the subform.
3. On the General tab of the Indexing Service Properties dialog box, in the Startup type drop-down item list, click Disabled.
4. Click OK.

If you use Index Server, you can exclude the Temporary ASP.NET Files directory from the folders that the Index Server scans. To do so, follow these steps:
1. Click Start, point to All Programs, point to Administrative Tools, and then click Computer Management.
2. Expand the Services and Applications node, expand the Indexing Service node, and then expand the System node.
3. Right-click the Directories folder, point to New, and then click Directory from the subform to open the Add Directory dialog box.
4. Click Browse, and then locate the Temporary ASP.NET Files directory. You typically find the Temporary ASP.NET files in the following path: c:\\Microsoft.NET\Framework\\Temporary ASP.NET Files
Note is the version of .NET Framework installed on your computer.
5. Click No under the Include in Index? option buttons.
6. Click OK to close.
7. Close the Computer Management dialog box.
8. Restart the Indexing Services service.

Solution #2 ~

In the web.config file if the tag identity impersonate=”true” is added, remove it and see. [Don't ask me why :)] [Ref: http://vadivel.blogspot.com/2006/06/access-is-denied-microsoftwebuiwebcont.html ]

5. I’m using EnterpriseLibrary latest version in my ASP.NET project. I used to get this error message “This schema for this assembly has not been registered with WMI.” while building my web project. Why?

Solution ~

  1. Open up the EnterpriseLibrary.sln and modify the Configuration Properties\Build\Conditional Constants of the EnterpriseLibrary.Common project.
  2. Remove the USEWMI;USEEVENTLOG;USEPERFORMANCECOUNTER constants. By removing these constants, all of the internal Enterprise Library instrumentation will be disabled.
  3. Recompile.

Ref : http://channel9.msdn.com/wiki/default.aspx/Channel9.EnterpriseLibraryFAQ

6. Protecting an ASP.NET page against malicious input with ValidateRequest (A potentially dangerous Request.Form value was detected)

When your project is in testing state, you should try to test your application by entering script tag (eg: <script lanague=”javascript”>) or HTML tag (eg: <html><strong>) or #@ or @# characters. And see what happen.. You may probably get the error.. If you don’t wanna get this error then you have to set the page directive validateRequest to false. Note that your page might has the security problem.

Ref: http://codebetter.com/blogs/peter.van.ooijen/archive/2005/10/21/133505.aspex

That’s all for now. If you have any useful tip for ASP.NET development, you can mail me at mchlsync AT gmail.com with the subject “[Michael Sync's blog - ASP.NET Tips]“. Thanks a lot.

Related Articles ~

  1. [Tips/Tricks] ASP.NET with SQL Reporting Services
  2. Tips/Tricks - How to control MaxLength of Multiline TextBox in ASP.NET 1.1?

[Tips/Tricks] ASP.NET with SQL Reporting Services

1. Error Message ~ d:\xxxxx\yourwebproject\yourreport.rdl
The value expression used in query parameter ‘@xxx’ returned a data type that is not valid.

Solution ~

  • Remove this parameter from Parameter
  • Rebuild the solution
  • (If you are still getting this error) Close and Reopen Visual Studio IDE ***

………………

2. Error Message ~ Parameter validation failed. It is not possible to provide valid values for all parameters. (rsParameterError) Get Online Help

Solution ~

  • Check “Has default” checkedbox in parameter lists of ReportViewer

***********

3. Problem: Report doesn’t get updated.

Solution ~

  • Add another parameter like “Timestamp” in your viewer.
  • Pass a timestamp field to your report from code.

Note: If you don’t wanna see this parameter “Timestamp” in your reportviewer, put blank for this report. (Be sure that you  have installed all required service packs.)

Tips/Tricks - How to control MaxLength of Multiline TextBox in ASP.NET 1.1?

Problem : The users can enter as much charaters as he wants in Multiline Textbox even MaxLength of this textbox is set to a particular value. Obviously, this is a bug of ASP.NET.

Details of problem : When the TextMode property of textbox is set to Multiline, the MaxLength property wont be handled in controlling the maximum length of users inputs.

maxlength-of-textbox-1.jpg

Demo Download

Steps to reproduce this issue (for those who doesn’t know that problem)

  1. Download Sample file
  2. Set “Problem.aspx” page as a startup page (There are two textboxes in this page. One is Multiline textbox (TextBox1.TextMode = Multiline) and another textbox is singleline textbox (TextBox2.TextMode = SingleLine). The MaxLength of Both textboxes are 10. )
  3. Run the project
  4. Type something more than 10 characters in both textboxes
    Observe: You can type as many characters as you wants in TextBox1 (1st Textbox) but not in Textbox2 (2nd Textbox)

Solution ~

This problem can be solved by using Javascript to track how many characters typed in textbox. If the length of characters are over limited number (max number) then we can simply ignore what the user type by returning “false” in javascript function.

Step #1. Put the following function in your page.


<script language="javascript">
function textboxMultilineMaxNumber(txt,maxLen){
try{
if(txt.value.length > (maxLen-1))return false;
}catch(e){
}
}
</script>

Step #2. Put the JS function in onkeypress event of Textbox.


&lt;asp:textbox id="TextBox1" runat="server" Width="232px" TextMode="MultiLine" Height="48px" style="Z-INDEX: 104; LEFT: 136px; TOP: 336px"
onkeypress=<strong>"return textboxMultilineMaxNumber(this,10)"</strong>></asp:textbox>

Run the sample

  1. Set “Solution.aspx” as startpage in the demo project that you just download.
  2. Run the project
  3. Type something more than 10 characters
    Observe: Both textboxes won’t let you type if the characters that you type are more than 10 as its defined.

HOW TO: Customizing YAHOO.UI.CALENDAR

Note: This post is published for those who like to add two more arrows for scrolling the year of calender.. And also, it’s a reply for this comment of my article in CodeProject.

Hello

I came across this article for my project as I had problems with ew:CalenderPopup control. The tutorial is very good and well explained.

However I noticed when clicking on the date picker button and the calender pops up. It has the blue arrows for each month to scroll by. Is there anyway I can put an extra arrows to scroll for year by year?

How can this be done please? Can you point me in the right directions of which file and what code to put in please?

Much appreciated for your help..

Thanks

Newbie….

HOW TO CUSTOMIZE THE HEADER OF YAHOO.UI.CALENDAR

Scenerio ~

1. Adding two arrows for scrolling the year of calendar.

Step #1: Adding two images in Images Folder of Project.

  1. calltyear.gif
  2. calrtyear.gif

Note: As I’m not very good at designing thing, I just changed the name of original image. It would be great if somebody can give me two arrows images.

Step #2: Changing the default imageroot in YAHOO.widget.Calendar_Core function

//Modified By: Michael Sync (http://michaelsync.net)
YAHOO.widget.Calendar_Core.IMG_ROOT = 'http://localhost/WebCalendarTest/Images';

Step #3: this.Config.Options

this.Config.Options = {
		// Configuration variables
		MULTI_SELECT : false,
		SHOW_WEEKDAYS : true,
		START_WEEKDAY : 0,
		SHOW_WEEK_HEADER : false,
		SHOW_WEEK_FOOTER : false,
		HIDE_BLANK_WEEKS : false,
		NAV_ARROW_LEFT : YAHOO.widget.Calendar_Core.IMG_ROOT + "callt.gif",
		NAV_ARROW_RIGHT : YAHOO.widget.Calendar_Core.IMG_ROOT + "calrt.gif",
		NAV_ARROW_LEFTYEAR : YAHOO.widget.Calendar_Core.IMG_ROOT + "calltyear.gif",
		NAV_ARROW_ RIGHTYEAR : YAHOO.widget.Calendar_Core.IMG_ROOT + "calrtyear.gif"
	};

Step #4: this.Config.Style

this.Config.Style = {
		// Style variables
		CSS_ROW_HEADER: "calrowhead",
		CSS_ROW_FOOTER: "calrowfoot",
		CSS_CELL : "calcell",
		CSS_CELL_SELECTED : "selected",
		CSS_CELL_RESTRICTED : "restricted",
		CSS_CELL_TODAY : "today",
		CSS_CELL_OOM : "oom",
		CSS_CELL_OOB : "previous",
		CSS_HEADER : "calheader",
		CSS_HEADER_TEXT : "calhead",
		CSS_WEEKDAY_CELL : "calweekdaycell",
		CSS_WEEKDAY_ROW : "calweekdayrow",
		CSS_FOOTER : "calfoot",
		CSS_CALENDAR : "yui-calendar",
		CSS_CONTAINER : "yui-calcontainer",
		CSS_2UPWRAPPER : "yui-cal2upwrapper",
		CSS_NAV_LEFT : "calnavleft",
		CSS_NAV_RIGHT : "calnavright",
		CSS_CELL_TOP : "calcelltop",
		CSS_CELL_LEFT : "calcellleft",
		CSS_CELL_RIGHT : "calcellright",
		CSS_NAV_LEFTYEAR : "calnavleftyear",
		CSS_NAV_RIGHTYEAR : "calnavrightyear",
		CSS_CELL_BOTTOM : "calcellbottom",
		CSS_CELL_HOVER : "calcellhover",
		CSS_CELL_HIGHLIGHT1 : "highlight1",
		CSS_CELL_HIGHLIGHT2 : "highlight2",
		CSS_CELL_HIGHLIGHT3 : "highlight3",
		CSS_CELL_HIGHLIGHT4 : "highlight4"
	};

Step #5: calendar.css

/* Added by Michael Sync (http://michaelsync.net)*/
.yui-calendar .calnavleftyear {
	position:absolute;
	background-repeat:no-repeat;
	cursor:pointer;
	top:2px;
	bottom:0;
	width:9px;
	height:12px;
	left:2px;
}
.yui-calendar .calnavright {
	position:absolute;
	background-repeat:no-repeat;
	cursor:pointer;
	top:2px;
	bottom:0;
	width:9px;
	height:12px;
	right:2px;
}
.yui-calendar .calnavleft {
	position:absolute;
	background-repeat:no-repeat;
	cursor:pointer;
	top:2px;
	bottom:0;
	width:9px;
	height:12px;
	left:12px; /* Midified By : Michael Sync */
}

.yui-calendar .calnavright {
	position:absolute;
	background-repeat:no-repeat;
	cursor:pointer;
	top:2px;
	bottom:0;
	width:9px;
	height:12px;
	right:12px; /* Midified By : Michael Sync */
}

Step #6: YAHOO.widget.Calendar.prototype.renderHeader

this.headerCell.innerHTML = "";

/*  Modified By: Michael Sync (http://michaelsync.net) */
//Nav Link for Previous Year
if (this.linkLeftYear) {
		YAHOO.util.Event.removeListener(this.linkLeftYear, "mousedown", this.previousYear);
}

this.linkLeftYear = document.createElement("A");
this.linkLeftYear.innerHTML = " ";
YAHOO.util.Event.addListener(this.linkLeftYear, "mousedown", this.previousYear, this, true);
this.linkLeftYear.style.backgroundImage =  "url(" + this.Options.NAV_ARROW_LEFTYEAR + ")";
this.linkLeftYear.className = this.Style.CSS_NAV_LEFTYEAR;

/*  Modified By: Michael Sync (http://michaelsync.net) */
if (this.linkLeft) {
  YAHOO.util.Event.removeListener(this.linkLeft, "mousedown", this.previousMonth);
}
   this.linkLeft = document.createElement("A");
   this.linkLeft.innerHTML = " ";
   YAHOO.util.Event.addListener(this.linkLeft, "mousedown", this.previousMonth, this, true);
   this.linkLeft.style.backgroundImage =  "url(" + this.Options.NAV_ARROW_LEFT + ")";
   this.linkLeft.className = this.Style.CSS_NAV_LEFT;

   if (this.linkRight) {
	YAHOO.util.Event.removeListener(this.linkRight, "mousedown", this.nextMonth);
  }
  this.linkRight = document.createElement("A");
  this.linkRight.innerHTML = " ";
  YAHOO.util.Event.addListener(this.linkRight, "mousedown", this.nextMonth, this, true);
  this.linkRight.style.backgroundImage = "url(" + this.Options.NAV_ARROW_RIGHT + ")";
  this.linkRight.className = this.Style.CSS_NAV_RIGHT;

   /*  Modified By: Michael Sync (http://michaelsync.net) */
  //Nav Link for Next Year
  if (this.linkRightYear) {
	YAHOO.util.Event.removeListener(this.linkRightYear, "mousedown", this.nextYear);
  }
	this.linkRightYear = document.createElement("A");
	this.linkRightYear.innerHTML = " ";
	YAHOO.util.Event.addListener(this.linkRightYear, "mousedown", this.nextYear, this, true);
	this.linkRightYear.style.backgroundImage =  "url(" + this.Options.NAV_ARROW_RIGHTYEAR + ")";
	this.linkRightYear.className = this.Style.CSS_NAV_RIGHTYEAR;

	headerContainer.appendChild(this.linkLeftYear);
	/*  Modified By: Michael Sync (http://michaelsync.net) */
	headerContainer.appendChild(this.linkLeft);
	headerContainer.appendChild(document.createTextNode(this.buildMonthLabel()));
	headerContainer.appendChild(this.linkRight);
	headerContainer.appendChild(this.linkRightYear); //Modified By Michael Sync
	this.headerCell.appendChild(headerContainer);

That’s all. :)
Downloads

WebCalendarTest + Year
WebCalendarTest + …
Hosted by eSnips

Getting All Users Information from Domain in ASP.NET

Step #1: Disable “Anonymous Access” of Virtual Directory

  1. Open Internet Information Service (IIS)
  2. Go to “Properties of your Virtual Directiory”
  3. Go to “Directory Security” tab
  4. Click “Edit” button of “Anonymous access and autherntication control”
  5. Uncheck “Anonymous access”

Step #2: Enabled impersonating in Web.Config
Add the tag below under in Web.config.


&lt;identity impersonate=&quot;true&quot;/&gt;

Step #3: Adding “System.Directory.Services” dll as reference

System.Directory.Services

Open ASP.NET Web project. And add this dll to your project.

Step #4: Put the following code in PageLoad

Code for getting all users from domain


try
{
   DirectorySearcher  searcher=new DirectorySearcher();
   string rootDSE=searcher.SearchRoot.Path;

   DirectoryEntry entry = new DirectoryEntry(rootDSE); //eg: Default Domain
   DirectorySearcher dirSearcher = new DirectorySearcher(entry);
   dirSearcher.Filter = "(&amp;(objectClass=user))";
   dirSearcher.SearchScope=SearchScope.Subtree;
   dirSearcher.Sort.Direction=System.DirectoryServices.SortDirection.Ascending;
   dirSearcher.Sort.PropertyName="cn";

   ArrayList domainMembers = new ArrayList();

   //Finding all users.
   foreach(SearchResult result in dirSearcher.FindAll())
   {
     try
     {
	string strUserInfo = string.Empty;
        DirectoryEntry de=result.GetDirectoryEntry();

	if(de.Properties.Contains("sAMAccountName"))
	  strUserInfo = de.Properties["sAMAccountName"].Value.ToString();

        domainMembers.Add(strUserInfo);
     }
     catch(Exception ex)
     {
	Console.WriteLine(ex.Message);
     }
   }
     DataGrid1.DataSource = domainMembers;
     DataGrid1.DataBind();
}
catch(Exception ex)
{
   Console.WriteLine(ex.Message);
}

You might get the following errors.

  1. An operations error occurred
  2. The specified domain either does not exist or could not be contacted

If you are getting these errors above, please make sure that you have permission to access your domain.

Download : http://michaelsync.net/demo/GetAllUsersFromDomain.zip

Hope it would help. Let me know if you have any problem with my code. Thanks.

Custom Javascript Dialog

Screenshot
hot-2.PNG

Source Code : http://michaelsync.net/demo/ComfirmDialogTest.zip

Introduction

This article describe how to create a Custom Javascript Dialog in ASP.NET. And also, I’m gonna tell you about my experience that I got when I was implementing this dialog in my project.

I’d highly recommend you to download my sample before reading. There are two samples in Demo Project that you can download. The first example is for implementing Javascript Prompt in ASP.NET. Even thought using Javascript Prompt is not a big deal, you can learn how to communicate between the client-side (JS) variable and Server-side (C#) variable, how to register Javascript in Content Page and so on. The second one is the main sample for this article. This sample will show how to create a Custom Javascript Dialog in ASP.NET, some tricks and so on. All coding and issues are discussed in details very well in this article.

What you should already known

  • ASP.NET 1.1 (C#) - esp: Page Template and DataGrid
  • Javascript and CSS

Understanding of Current Sytem

There is one listing page in the sytem. This page allows the user to delete multiple records at a time. The user has to enter a comment for the reason why he/she wants to delete those records. It can be done very easily in ASP.NET by using DataGrid with checked boxes. ( plus one textbox for comment and one button for deleting) Unfortunetly, our client is not happy with having one extra textbox for filling a comment in this page cuz of some UI issues. They more perfer to have something like Javascript Popup window with nice UI in this page.

Our Goals

  1. Showing Javascript Dialog : The Main Goal is that showing nice javascript dialog when the user click the “Delete” button. [Showing Popup in Javascript is not that difficult but we have other requirement too.].
  2. Handling the sequence of the events :Since we are already written the code for Deleting the records in Server-side, this code (C#) should be executed after executing the client-script.
  3. Accessing the client-side variable from Service-side, The comment text has to be accessible from Server-side code.

Javascript Prompts

var str = prompt('Please Enter the comments!');

Prompt” is a build-in function in Javascript to show a window like that below picture. It’s extremely easy to use. Another advantage is that the Server-side won’t be executed as long as this prompt is showing. The Server-side will be executed ONLY if the user click “OK” or “Cancel” so that we don’t need to any trick or hack to pause the Server-side executing.

javascript-prompt.PNG

Okay. Let’s start coding! (I’m gonna use the basepage class that I have used in this sample (zip file no #1).) Firstly, we write a Javascript function called “AskForComment” as below.
Note that we have to check whether the user cancel the operation or not.

(Refer to Blue line. we are checking three condition in this line.

  1. (str == ”) is checking whether the user fills anything or not. Actually, we should trim this variable.
  2. ( str == ‘undefined’) is also checking the same thing. only different is that ‘undefined’ is the default value of prompt in IE.
  3. ( str == null) is checking whether the user click “Cancel” button or not.) If the user doesn’t fill anything or click “Cancel” then our function is gonna return “false”, which means there wont be any further execution.
<script language="javascript">
function AskForComment(){
  var str = prompt('Please Enter the comments!');
  if((str == '') || ( str == 'undefined') || ( str == null))
    return false;
  else{
    return true;
  }
}</script>

Accessing the Client-side variable (variable named “str” in this sample ) from Server-side Code

Here, we have one problem in accessing the javascript variable called “str” from Server-side code. So, we need to have one inferface that can be accessible from both Client-side and Server-side. So, I decide to use a Hidden Field as an interface in this sample and named it “hiddenComment” and also change this HTML Hidden Control to Server side control by adding “runat=”server”. Now, we have a control that can be accessed from Javascript and Server-side script (C#).

The following changes (in blue color) we need to made in our Javascript for getting the object of Hidden Field. (Note that _ctl5_hiddenComment is the ClientID of Server-side Hidden Field.)

<script language="javascript">
function AskForComment(){
  var str = prompt('Please Enter the comments!');
  if((str == '') || ( str == 'undefined') || ( str == null))
      return false;
  else{
      document.forms['frmBase'].elements['_ctl5_hiddenComment'].value = str
      var obj = document.getElementById('_ctl5_hiddenComment');
      obj.value = str;
      return true;
  }
}</script>

We just finished writing the Javascript as above with the required feature. But I think that it’s better if we register this Javascript function in Page_PreRender event since the ClientId of Server-side Hidden Field might be changed anytime. (If you dont know how to register the Javascript Function in Page_PreRender Event, please take a look at SampleControl1.ascx in Sample Project. You will see the completed code in SampleControl1_PreRender Event.)

After that, there is only two things we need to do. First one is that we have to attach our Javascript Function in “Delete” button.

btnDelete.Attributes.Add("onclick", "return AskForComment();");

Note: “return” is very important here. Because we dont want any further execution in case the user click “Cancel”.

Then, the last thing is that we have to check whether we are able to get the value of Hidden Field in the Click Event of “Delete” Button.

private void btnDelete_Click(object sender, System.EventArgs e)
{
  Console.WriteLine(hiddenComment.Value);
}

Demo

Please open the page called “Sample1.aspx” from my sample. Set the breakpoint at the Click event of “Delete” button. Then, run the web project.

There are one DataGrid with Checkboxes in this page “Sample1.aspx”. If you click the “Delete” button then the Javascript Prompt will be shown for asking the comment. Type something you want and click “OK” button. Then, the Click event of “Delete” button will be fired. Now, you can check the value of Hidden Field “hiddenComment”. You will get the text that you type in Prompt.

*** Note: I didn’t use any database for the data that suppose to be in DataGrid. I have created two classes called “Person” and “Persons” in this sample. and All data from Persons class will be binded to DataGrid.

In the Click Event of “Delete” button, I didn’t put anything related to Database. But you will find the code for getting the value of hidden field and getting the selected item of DataGrid.

Okay. We have just done. But the main disadvantage that I really don’t like is that it doesn’t look good. It looks very different from the existing UI of our current system. So, We will think about other way.

Custom Javascript Dialog

js-dialog.PNG

As you all know, there are a lot of Opensource Javascript **box in Internet. They all have their pros and cons. Some Javascript Libraries or toolkits have a lot of features such as Ajax support, DOM, Animation, Drag and Drop and so on. but they are not Light weight. In our sample, we just need to create one Custom Javascript Dialog . We dont any other features and we dont wanna load a ton of javascript objects (which won’t be used anyway) in web broswer.

So, I’m just going though the source code of Javascript Toolkit and I come to know that Greybox Redux is pretty good toolkit and has very sample implementation.

but one thing I don’t like is that this toolkit is using IFrame. As IFrame is using in it, we might properly need to have one extra page to show in IFrame. However, we don’t like to have one extra page in our System. So, I decide to use HTML Table instead of IFrame since I don’t need to show anything dynamic on this dialog.

Okay. Let’s start!

Creating HTML Window

Before we start creating a custom dialog dynamically, we should start creating a static dialog in HTML.

In Head Tag ~

#GB_window {   top: 10px;   left: 0px;   position: absolute;   background: #fff;   border: 5px solid #aaa;   overflow: auto;   width: 410px;   height: 158px;   z-index: 150; }

#GB_caption {   font: 12px bold helvetica, verdana, sans-serif;   color: #fff;   background: #888;   padding: 2px 0 2px 5px;   margin: 0;   text-align: left; }

#GB_window img {   position: absolute;   top: 2px;   right: 5px;   cursor: pointer;   cursor: hand; }

In Body Tag ~


<div id='GB_window'>
<div id='GB_caption'>Confirm Dialog</div>
<img src='close.gif' alt='Close window' '/>
<div id='definition'>
<table border='0' width='400' height='130' cellspacing='0' cellpadding='0'
ID='Table1'>
<tr>
<td height='23' width='18'> </td>
<td height='23' width='446'> </td>
<td height='23' width='31'> </td>
</tr>
<tr>
<td height='24' width='18'> </td>
<td height='24' width='446'><font face='Verdana' size='2'>Please fill
the reason for deleting records!</font></td>
<td height='24' width='31'> </td>
</tr>
<tr>
<td height='23' width='18'> </td>
<td height='23' width='446'><input type='text' name='T2' size='57'
ID='Text1'></td>
<td height='23' width='31'> </td>
</tr>
<tr>
<td height='23' width='18'> </td>
<td height='23' width='446'>
<input type='button' value='Delete It!' name='B4' ID='Button1' ></td>
<td height='23' width='31'> </td>
</tr>
<tr>
<td height='23' width='18'> </td>
<td height='23' width='446'> </td>
<td height='23' width='31'> </td>
</tr>
</table>
</div>

</div>

Output will be as following image.

dialog-output.PNG

Note:

  1. DIV “GB_Window” and CSS “#GB_window” is for base dialog.
  2. DIV “GB_caption” and CSS “#GB_caption” is for the Caption of Dialog. For example: if you wanna have “blue color” (instead of “grey color”) for the background of capture, you can simply change the color value in CSS of #GB_caption.
  3. CSS #GB_window img is for “Close” image that you can replace with any picture. The current image is not the original image of Grey Redux. I made it a lit bit smaller.
  4. All tags within the div “definition” are the content of dialog. For example, if you dont want one text, one textbox and button to show in dialog, you can replace with anything you want.

Implementing Custom Javascript Dialog in ASP.NET

Please open the HTML View of TestContentPageControl.ascx from the sample project that you downloaded. (As there are a lot of code in this page, I won’t paste all coding here.)

There is one div called “div1″. This is a placeholder where our Custom Javascript Dialog suppose to be displayed. ( As I wanna use “InnerHTML” instead of using “HTML DOM”, you put this div in this page. ) You may notice that the style of this DIV.

  1. DISPLAY: none; This DIV should not show until the user click the “Delete” button.
  2. Z-INDEX: 111; If there are other controls placed on your page, you should set the highest value of this style. otherwise, the custom dialog will be shown behind the other controls.
  3. POSITION: absolute; this is a must since we wanna show the dialog at the center of page

You may also find the hidden input called “hiddenComment” in TestContentPageControl.ascx. The main thing is that this control has to be a Server-side control. So, both client-side script (js) and server-side script (C#) are able to access this control. (I already explain about the use of Server-side Hidden Field earlier.)

After viewing the HTML view of ascx file, we should go and check the PreRender event of page “TestContentPageControl_PreRender”.

There are three javascript functions (hideWindow(), showWindow() and deleteit()) in this event. (You may notice the variable called g_IsWindowShown in this event. I will explain about it later. For the time being, we will just focos on showing and hiding the JS dialog.)

Understanding of hideWindow() Javascript Function

This function is very simple. When the user click “close” image or “cancel” button then we set the “Display” style of div1 to “none”.

Understanding of showWindow() Javascript Function

The following lines is used for getting the clientWidth and setting the dialog at the center of the page.

var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
var oDiv = document.getElementById('div1');
oDiv.style.left = ((w - 410)/2) + 'px';

Then, we declare the variable called str in this function and we will append the HTML code ( that I show in “Creating HTML Window” ) to this variable.

After that, we set this varible to the inner text of div1. (oDiv.innerHTML = strWin;) then, we show this DIV in browser.

Here, we have one problem. After showing our Javascript Dialog, the execute goes to the Server-side. (It is not like that Javascript Prompt. When we are using Javascript Prompt, the execution is paused as long as this prompt is showing.) So, we need some tricks for pausing the execution and re-running the execution.

Trick #1

The javascript variable called “g_IsWindowShown” is declared for this purpose.
As the JS Dialog doesn’t show by default, the default value of this variable become “false”. When the user click “Delete” button, we show the JS Dialog and set this variable to true. **But we return “false” in ShowWindow() function. (so that the execute wont’ go to Server-side.)

If the user click “cancel” or “close” image, we call “hideWindow()” function. In this function, we hide the JS dialog and set the variable “g_IsWindowShown” to true. (We also return “false” in this function since we dont want the Server-side code to execute.)

If the user click “Delete It” button then we call “deleteit()” function. In this function, we set the text of textbox to hidden field so that this value can be read from Server-side script. then, we fire the button client event of “Delete” button (not “Delete It” button.) then, showWindow() function will be invoked again. At that time, the variable “g_IsWindowShown” will be true. After that, we just return “true” from this function. So, the Server-side code will be executed. Here is the end of our trick. :)

Demo

- Please open the Demo Project.
- Set the breakpost at btnDelete_Click.
- Please run “TestContentPage.aspx” in Demo Project.
- Select some checkedboxes in the Grid.
- Click “Delete” button
- Type the comment
- Click “Delete It” button in Javascript Dialog.
Ob: The Click event of btnDelete will be invoked and you can check the value of hidden field to see what comment you hav filled. and also, you can see which checkedboxes you have selected.

Conclusion

Sorry if you think that my article is too long.. (plus my writing is also not very interest. :) ) Anyway, I try to explain as much clear as I can and hopefully, you will find it useful.. Please let me know if you have suggestions or comments..