Monday, April 20, 2015

How to use asp.net user control to design a dynamic data loading message template for email Body in asp.net?

if you want to send an email confirmation to the submission, with those user input data being sent and saved in the database.  it is a good approach to use the asp.net custom user control to layout the design of the message template according the user requirement.

we will create a custom asp.net user control naming it as MCustomUC. it will be shown as MCustomUC.ascx in your project file.

In the code behind, define a public property such the uniqure record ID, that we can pass from the host page to the user control, here is the snippet of code from the user control code behind.

 public string UniqueConfirmedID
        {
            get;
            set;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        public void LoadData()
        {
            VehicleProvider vehicleProvider = new VehicleProvider();
            List<DealerVehicle> myList = vehicleProvider.GetProgramDetailsByID(ConvertToInteger(UniqueConfirmedID));
            if (myList != null && myList .Count > 0)
            {
                BindControls(myList [0]);
             }
        }

in the submission page, we can dynamically load the user control after the confirmation id is generated

 private string LoadEmailContent(string myID)
        {
            StringBuilder sb = new StringBuilder();
            MCustomUC myCustomUC = (MCustomUC)LoadControl("~/UserControls/MCustomUC .ascx");
            myCustomUC .ID = "emailContentDetail";
            myCustomUC .UniqueConfirmedID= myID;
            myCustomUC .LoadData();
           
            // Render the control into the stringbuilder
            StringWriter sw = new StringWriter(sb);
            Html32TextWriter htw = new Html32TextWriter(sw);
            myCustomUC .RenderControl(htw);
            string body = sb.ToString();
            return body;
        }

then we can call the above method and assign the output string to the email body property of the .net mail object. the user will receive the desired email message with the predefined template.



No comments:

Post a Comment