2011-08-03 2 views
0

전자 메일을 보내야하는 프로젝트에서 작업하고 있습니다. 메일 형식은 ascx Usercontrol에서 이루어졌으며 컨트롤은 이름과 날짜 같은 특정 변수가 다른 방법으로 채워지는 전자 메일 본문을 렌더링하는 데 사용됩니다.UserControl 개체 asp.net 렌더링 C#

내 주요 문제는 클래스 및 메서드의 개체와 함께 전자 메일 본문에 컨트롤을 렌더링하려는 것입니다. 사실 MVC 방식으로하고 싶습니다 (예 : 프런트 엔드에서 모델 전달). 이렇게하는 좋은 방법이 있습니까?

는 다음과 내가 사용하고 코드가 될 때 :

string path = "Email Template/LeaveRequestedEmailToAPPREC.ascx"; 
body = RenderUserControl(path,lrd); 
MailMessage msg = new MailMessage(); 
try 
{ 
    msg.From = new MailAddress(fromemail, fromname); 
    msg.To.Add(toemail); 
    msg.Subject = subject; 
    msg.Body = body; 
    msg.IsBodyHtml = true; 
    SmtpClient sc = new SmtpClient(); 
    sc.Host = "smtp.ntc.net.np"; 
    sc.Port = 25; 
    sc.Send(msg); 
    msg.Dispose(); 
    msg = null; 
    return true; 
} 



//======== Rendering the UserControl ========== 
public string RenderUserControl(string path,object viewmodel) 
{    
    Page holder = new Page(); 
    UserControl viewControl = (UserControl)holder.LoadControl(path); 

    HtmlForm tempForm = new HtmlForm(); //if the UserControl contain some server controls like TextBox, Button, Add a form wrapped them. 
    tempForm.Controls.Add(viewControl); 
    holder.Controls.Add(tempForm); 

    StringWriter output = new StringWriter(); 
    HttpContext.Current.Server.Execute(holder, output, false); 
    string outputToReturn = output.ToString(); 
    output.Close(); 
    return outputToReturn; 
} 

답변

0

나는 당신이 완전히 원하는 것을 정확히 파악하고있어 확실하지 않다,하지만 당신은 같은 모든 컨트롤에 의해 노출되는 RenderControl 방법을 사용하여 시도 할 수 있습니다 예 :

using (var buffer = new MemoryStream()) 
{ 
    var builder = new System.IO.StreamWriter(buffer); 
    using (var stream = new HtmlTextWriter(builder)) 
    { 
     holder.RenderControl(stream); 
    } 
    return builder.ToString(); 
}