Asp.net| Tips We often use JavaScript scripts for ASP.net development, such as:
private void Button1_Click (object sender, System.EventArgs e)
{
Response.Write ("<script language= ' JavaScript ' >alert (' OK ');</script>");
}
It is often repeated to write these scripts, if we can make a corresponding function is good, directly can be used. Many people have their own JavaScript functions, but most of them are like this:
<summary>
Server-side Pop-up Alert dialog box
</summary>
<param name= "Str_message" > Message, Example: "Please enter your name!" </param>
<param name= "page" >page class </param>
public void Alert (String str_message,page Page)
{
if (!page. IsStartupScriptRegistered ("Msgonlyalert"))
{
Page. RegisterStartupScript ("Msgonlyalert", "<script>alert" (' +str_message+ ");</script>");
}
}
However, the use of the time, each time to inherit this class, use or some trouble, if the function is static function, class is static class, we do not inherit can be used. But how do we write it?
Take a look at this piece of code
#region public static void MessageBox (Page page, string msg)
///
Pop-up dialog box
///
A pointer to the current page, typically this
News
public static void MessageBox (Page page, string msg)
{
StringBuilder strscript = new StringBuilder ();
Strscript.append ("<script language=javascript>");
Strscript.append ("alert (' + msg + ');");
Strscript.append ("</script>");
if (! page). IsStartupScriptRegistered ("MessageBox"))
{
Page. RegisterStartupScript ("MessageBox", strscript.tostring ());
}
}
#endregion
In this way, we can easily use a lot of existing JS scripts.
PS: In fact, many commonly used methods can be written as a static function to invoke. I will attach a few examples as a reference.
MD5 Encryption:
///
MD5 Encrypt
///
Text
MD5 Encrypt string
public string Md5encrypt (string strText)
{
MD5 MD5 = new MD5CryptoServiceProvider ();
Byte[] result = Md5.computehash (System.Text.Encoding.Default.GetBytes (StrText));
return System.Text.Encoding.Default.GetString (Result);
}
To take a random number of a specified length:
#region public static string getrandnum (int randnumlength)
///
Get random numbers
///
The length of a random number
///
public static string Getrandnum (int randnumlength)
{
System.Random randnum = new System.Random (unchecked ((int) DateTime.Now.Ticks));
StringBuilder sb = new StringBuilder (randnumlength);
for (int i = 0; i < randnumlength; i++)
{
Sb. Append (Randnum.next (0, 9));
}
Return SB. ToString ();
}
#endregion