Add JQuery, Javascript, CSS to ASPx User Controls parent

Category : ASP.Net, C#, JQuery/JScript

This is my preferred method. (Microsoft has controls such as ScriptManager and ScriptManagerProxy but like nearly everything they do, I believe its overkill) To me, this is the simplest method.

The Problem: You want to convert or to create a user control that has scripts and/or css.

Solution: Within the Page_Load event of the user control, simply include the following:

    //For Scripts - notice we add this script call to the PARENT HEADER
    LiteralControl jQuery = new LiteralControl();
    jQuery.Text = "<script type=\"text/javascript\" src=\"js/jquery.js\"></script>";
    Page.Header.Controls.Add(jQuery);
 
    //For CSS - You could add Media under attributes as well.  
    HtmlLink stylesLink = new HtmlLink();
    stylesLink.Attributes["rel"] = "stylesheet";
    stylesLink.Attributes["type"] = "text/css";
    stylesLink.Href = "css/yourPagesCSS.css";
    Page.Header.Controls.Add(stylesLink);

Hope this helps someone! t

Getting a .net System.Drawing color from a Hex value.

Category : ASP.Net

So I’m using a jquery color picker, got to the back code where I was going to grab my colors and thought for a minute that there was no way to convert my HEX to one of the .Net system colors… (what am I thinking, WE should always remember that there is more than likely some class available to do what you need, as was the case here!)

SO YOU got a hex and need it to convert to a system color? Here ya go:

System.Drawing.ColorTranslator.FromHtml(“#FFFFFF”);

Thank you .Net
T

Send JSON via AJAX to JQuery from an aspx page.

Category : ASP.Net, JQuery/JScript

This took me many tries to get this right so I am logging this so I dont have to go through this again.

JSON (Javascript Object Notation) allows us to send data to our Javascript (JQuery) and let it read that data in very useful ways.  With JSON, we can send basic keys and values to Javascript (as I will show here) up to complete objects with parameters and functions ( just google JSON tutorials to see some amazing ways to use the data).

HERE I will show the following scenario:  using an aspx page (but it could just as easily be a simple html page) I declare the JQuery library and  using JQuery on that page  I make a call to another aspx page (so we can get to the server and do ‘thinking’ stuff) using one of JQuerys Ajax functions  (“$.post”) -  In that CALLED page I will be grabbing any sent in data (because our JQuery can send data to that page) , doing WHATEVER you want to do with the data (tap into a database, apply business rules, etc.) and then formatting whatever data you want to return in JSON format so that our JQuery can use it in a somewhat intelligent fashion.

I probably lost many of you, so let me just SHOW you and it will be much clearer.

STEP 1:  Markup – add the JQuery Library to your page, then call the $.post function (that function can take several types of configurations but the one I am using is the NAME of the page I am calling, the data I am sending to it, what to do with the Results I get back, and finally telling it that the results WILL BE IN JSON format.

<head runat="server">
    <title>JSON Test Page</title>    
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
 
    $(document).ready(function() {
        $("#jsonButt").click( function() {
                  $('#jsonReturnDiv').html( '<img src="images/loading.gif" />' );  
 
                  $.post('ajax/jsonTestPage.aspx',         
                        {'ThisIsWhereIWouldSendDataIn' : 'Data1', 'Data2Etc' : 'Data2'},  
                      //The data we return will come back as JSON
                       function(data) {                            
                           $('#firstReturnDiv').html(data.first);
                           $('#secondReturnDiv').html(data.second);
                           $('#thirdReturnDiv').html(data.third);
                           $('#jsonReturnDiv').html( '' );  
                        }, "json");
              });
 
     });  
     </script> 
</head>
<body>
    <form id="form1" runat="server">
        <div id="firstReturnDiv"> This is the first return div... check it</div>
        <hr />
        <div id="secondReturnDiv"> This is the second return div... check it</div>
        <hr /> 
        <div id="thirdReturnDiv"> This is the third return div... check it</div>       
        <hr />
        <input id="jsonButt" type="button" value="button" /> <div id="jsonReturnDiv"></div>
    </form>
</body>
</html>

If you dont understand the Document ready, butt click, and the rest then you should probably just read a couple QUICK JQuery tutorials — its very simple to pick up and very worthwhile. Basically the .click function is what Kicks the whole thing off so that when a user clicks a button on my page that I have set the ID to ‘jsonButt’. (I also kick off a lovely little whirly gig [ i love whirly gigs ] that I eventually hide after the data comes back) ….

STEP 2: Code Behind – So inside of my aspx page (the one I point to in the $.post function ( ‘ajax/jsonTestPage.aspx’, ) I remove ALL markup and only leave my top line “<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jsonTestPage.aspx.cs" Inherits="ajax.jsonTestPage" %>” . Then in code behind I can grab the data that was sent in to the page via the Query string (I dont do this here) … the format the JSON data to return BACK to the page. *** TWO THINGS MUST BE PRESENT TO MAKE THIS WORK : THE CONTENT TYPE MUST BE SET AS I HAVE HERE AND THE JSON DATA HAS TO BE SURROUNDED BY DOUBLE QUOTES

        protected void Page_Load(object sender, EventArgs e)
        {
           // Response.ClearHeaders();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            //JSON MUST BE SENT BACK WITH THIS CONTENT TYPE!
            Response.ContentType = "application/json"; 
            //JSON MUST HAVE DOUBLE QOUTES!!!
            string jsonReturn = "{\"first\":\"This is the first\", \"second\":\"This is SECOND!\", \"third\" : \"This is third!\"}";
            Response.Write(jsonReturn);
        }

Now look at the jsonReturn string. We have a piece of data called ‘first’ and it’s value ‘This is the first’, etc… here is where we could make more complicated objects but we will keep it simple for now.

STEP 3 – This isnt really a step but just some explanation… The Response.Write now sends the data back to the page in JSON format. If you look again at our $.post function you will see that the return data (which we have appropriately named ‘data’) will be used here:

function(data) {
$(‘#firstReturnDiv’).html(data.first);
$(‘#secondReturnDiv’).html(data.second);
$(‘#thirdReturnDiv’).html(data.third);
$(‘#jsonReturnDiv’).html( ” );
},
Take note of how we were able to use the data simply now by calling data.first, data.second, etc… again, this is a simple (although elegant) use. This allows us to do many advanced things with our return data. We could even return an array of multiple objects and be able to use and manipulate and display them straight from Javascript.

Using this technique, one could write an elegant front end using ONLY JQuery and HTML while still being able to harness the power of IIS on the back end. Hope this helps someone! T.

C# – How to get Page Life Cycle Events

Category : ASP.Net, C#

Use “override” keyword and make sure that your AutoEventWireup is set to True in Markup.

And there you go!

Ciao!

Controlling the SRC of an IFRAME from code behind.

Category : ASP.Net, C#, VB.Net

Make sure to add the ” runat=’server’ ” in the markup.

 myIFrame.Attributes["src"] = "http://www.google.com";

How to get the parameters from your Stored Procedures in code behind.

Category : ADO / SQL, ASP.Net, C#

THE KEY LINE BELOW IS : SqlCommandBuilder.DeriveParameters(cmd);

SqlConnection c = new SqlConnection(TextboxConnString.Text);
 
//NAME OF STORED PROC
string sql = DropdownStoredProcs.Value.ToString();
 
SqlCommand cmd = new SqlCommand(sql, c);
cmd.CommandType = CommandType.StoredProcedure;
 
c.Open();
SqlCommandBuilder.DeriveParameters(cmd);
foreach (SqlParameter param in cmd.Parameters)
{
     if ((param.Direction == ParameterDirection.Input) || (param.Direction == ParameterDirection.InputOutput))
     {
         //Notice that I can get the Name of the parameter as well as it's DBType...
         string paramDescription = param.ParameterName + " | " + param.SqlDbType.ToString();
         DropdownSPParameters.Items.Add(paramDescription, param.ParameterName);
     }
}
c.Close();

Creating a TABLE in the code behind.

Category : ASP.Net, C#

This worked well for me.  I created the TABLE in markup [MAKE SURE ITS AN ASP:TABLE with the runat server tag].

Then you can manipulate it from code-behind like so:

   TableRow tr = new TableRow();
   TableCell tc = new TableCell();
   Label label2 = new Label();
   label2.Text = "LAJLKFJDSLJFLKDF";
   tc.Controls.Add(label2);
   tr.Cells.Add(tc);
   MyTable.Rows.Add(tr);

Hope this helps!

ASP.Net Page Lifecycle (page events)

Category : ASP.Net

I am not even going to try — here is the best and most complete description of the Page Lifecycle.

http://69.10.233.10/KB/aspnet/ASPNET_Page_Lifecycle.aspx (very nice and thanks UsualDosage)

Although I will list the Acronym that may help those of you who just need a quick reminder…. try this

  • S – Start
  • I  – Initialize
  • L  – Load
  • V – Validate
  • E – Event Handling
  • R – Render

caio

Creating and manipulating a dataTable

Category : ASP.Net, VB.Net

This structure keeps coming up :

 dsSchools = mydata
 
'Create table to bind to dataGrid
Dim dt As New DataTable
Dim nameCol, activeCol As New DataColumn
dt.Columns.Add(nameCol)
dt.Columns.Add(activeCol)
Dim dRow As DataRow = dt.NewRow
 
For Each dr As DataRow In dsSchools.Tables(0).Rows
       If Not dr("title") Is DBNull.Value Then dRow(nameCol) = dr("title")
       If Not dr("IsActive") Is DBNull.Value Then dRow(activeCol) = dr("isActive").ToString
       dt.Rows.Add(dRow)
Next

How to force IE8 Compatability View

Category : ASP.Net

IE8 has issues with many pages and it’s formatting.

So if you want IE8 to look like IE7 you can embed a meta tag in your pages.

What I have found is that the meta tag needs to be right under the <title> tag in your head before anything else.

Here’s the tag : <meta http-equiv=”X-UA-Compatible” content=”IE=EmulateIE7″ />

Hope this helps!