C# Alert JavaScript วีธีแสดง Alert Javascript ใน Code Behide

9-3-2015 3-12-22 PM

สามารถทำได้โดยแก้ไขในไฟล์ Code Behide ตามตัวอย่างด้านล่าง

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RegisterAlertScript("ทดสอบ Alert JavaScript");
    }

    public void RegisterAlertScript(String sText)
    {
        String csname1 = "PopupScript"+DateTime.Now;
        Type cstype = this.GetType();
        ClientScriptManager cs = Page.ClientScript;
        if (!cs.IsStartupScriptRegistered(cstype, csname1))
        {
            StringBuilder cstext1 = new StringBuilder();
            cstext1.Append("<script type=text/javascript> alert('"+ sText + "') </");
            cstext1.Append("script>");
            cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
        }
    }
}

กรณีเอาไว้ใน Class File จะต้องประกาศ HttpContext.Current.Handler ก่อน ดังตัวอย่างด้านล่าง

public void RegisterAlertScript(String sText)
    {
        String csname1 = "PopupScript" + DateTime.Now;
        Type cstype = this.GetType();
        Page page = HttpContext.Current.Handler as Page;
        ClientScriptManager cs = page.ClientScript;
        if (!cs.IsStartupScriptRegistered(cstype, csname1))
        {
            StringBuilder cstext1 = new StringBuilder();
            cstext1.Append("<script type=text/javascript> alert('" + sText + "') </");
            cstext1.Append("script>");
            cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
        }
    }

 

 

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.