2016-06-25 2 views
0

나는이 웹 사이트에서 특정 이메일 주소로 이메일을 직접 보낼 수있는 ASP.NET MVC를 사용하여 웹 사이트에서 작업 해 왔습니다. 정상적으로 작동하지만 전자 메일 (예 : 이름, 전자 메일 주소 등)에 전송되는 정보에는 데이터베이스가 없습니다. 그래서 데이터베이스를 추가하려고 시도했지만 어떻게 든 작동하지 않으며 몇 가지 오류가 계속 발생합니다. 전자 메일을 보낼 수 있는지, 동시에 데이터베이스에 저장할지 여부는 확실하지 않습니다. 내가하는 일에 뭔가 이상한 점이있어서 누군가 나를 도와주세요. 고맙습니다.이메일을 보내 데이터베이스 (ASP.NET MVC)에 저장

다음은 이메일의 전송에 대한 내 컨트롤러 :

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files) 
    { 
     if (ModelState.IsValid) 
     { 
      RegisterRepository regRepo = new RegisterRepository(); 

      if (regRepo.Register(model)) 
      { 
       List<string> paths = new List<string>(); 

       foreach (var file in files) 
       { 
        if (file.ContentLength > 0) 
        { 
         var fileName = Path.GetFileName(file.FileName); 
         var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
         file.SaveAs(path); 
         paths.Add(path); 
        } 
       } 

       var message = new MailMessage(); 
       foreach (var path in paths) 
       { 
        var fileInfo = new FileInfo(path); 
        var memoryStream = new MemoryStream(); 
        using (var stream = fileInfo.OpenRead()) 
        { 
         stream.CopyTo(memoryStream); 
        } 
        memoryStream.Position = 0; 
        string fileName = fileInfo.Name; 
        message.Attachments.Add(new Attachment(memoryStream, fileName)); 
       } 

       //Rest of business logic here 
       string EncodedResponse = Request.Form["g-Recaptcha-Response"]; 
       bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false); 
       if (IsCaptchaValid) 
       { 

        var body = "<p><b>Email From:</b> {0} ({1})</p><p><b>Message:<b></p><p>{2}</p>"; 
        message.To.Add(new MailAddress("***@gmail.com")); // replace with valid value 
        message.From = new MailAddress("***@ymailcom"); // replace with valid value 
        message.Subject = "YesDubai.org (REGISTRATION)"; 
        message.Body = string.Format(body, model.Talent_Name, model.Talent_Email, model.Talent_SelfPromotion); 
        message.IsBodyHtml = true; 
        using (var smtp = new SmtpClient()) 
        { 
         var credential = new NetworkCredential 
         { 
          UserName = "***@gmail.com", // replace with valid value 
          Password = "***" // replace with valid value 
         }; 
         smtp.Credentials = credential; 
         smtp.Host = "smtp.gmail.com"; 
         smtp.Port = 587; 
         smtp.EnableSsl = true; 
         smtp.SendCompleted += (s, e) => 
         { 
          //delete attached files 
          foreach (var path in paths) 
           System.IO.File.Delete(path); 
         }; 
         await smtp.SendMailAsync(message); 
         ViewBag.Message = "Your message has been sent!"; 

         ModelState.Clear(); 
         return View("Register"); 
        } 
       } 
       else 
       { 
        TempData["recaptcha"] = "Please verify that you are not a robot!"; 
       } 

      } return View(model); 

     } 
    } 

을 그리고 여기에 모달 클래스의 :

public partial class TalentInfo 
{ 
    [Display(Name = "ID")] 
    public int TalentID { get; set; } 
    [Display(Name = "Talent's Name")] 
    public string Talent_Name { get; set; } 
    [Display(Name = "Email Address")] 
    public string Talent_Email { get; set; } 
    [Display(Name = "Self Promotion")] 
    public string Talent_SelfPromotion { get; set; } 
} 

그리고 여기 저장소입니다 :

public class RegisterRepository 
{ 

    //SqlTransaction transaction = null; 
    private SqlConnection con; 
    //To Handle connection related activities 
    private void connection() 
    { 
     string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(); 
     con = new SqlConnection(constr); 


    } 


    internal bool Register(TalentInfo model) 
    { 
     throw new NotImplementedException(); 

     connection(); 

     try 
     { 
      SqlCommand com = new SqlCommand("SP_INSERT_TALENT_INFO", con); 
      com.CommandType = CommandType.StoredProcedure; 
      com.Parameters.AddWithValue("@Talent_name", model.Talent_Name); 
      com.Parameters.AddWithValue("@Talent_email", model.Talent_Email); 
      com.Parameters.AddWithValue("@Talent_SelfPromotion", model.Talent_SelfPromotion); 
      con.Open(); 
      int i = com.ExecuteNonQuery(); 
      con.Close(); 
      if (i >= 1) 
      { 
       return true; 
      } 
      else 
      { 

       return false; 
      } 


     } 

     catch 
     { 
      return Register(model); 
     } 
     finally 
     { 
      con.Close(); 
     } 

    } 


} 
+1

를 오류 뭐죠? 붙여 넣기 –

+0

@AbdulRehmanSayed ** TalentInfo, System.Collections.Generic.IEnumerable ) ': 모든 코드 경로가 값을 반환하지는 않습니다. 도움 주셔서 감사합니다. –

+2

(ModelState.IsValid)가 false로 평가되면 등록 메소드가 값을 반환하지 않습니다. –

답변

2

이 단순히 컴파일입니다 오류. 코드의 모든 경로에서 결과를 반환해야합니다. (ModelState.IsValid)이 false로 평가되면 때

1) 뭔가를 돌려 :

당신은 당신의 코드에서이 오류가 여기

[HttpPost] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files) 
{ 
    if (ModelState.IsValid) 
    { 
     //you have lots of code here.... 
    } 
    else 
    { 
     //you need to return something here....because (ModelState.IsValid) might be false 
    } 
} 
+0

감사합니다. 오류가 수정되었습니다. 이메일이 제대로 전송되었지만 어떻게 든 데이터베이스에 저장되지 않습니다. 선생님, 도와 주실 수 있기를 바랍니다. 고맙습니다. –

1

return 누락있다. 레지스터 방법에

2)이 제거 라인 :

throw new NotImplementedException(); 
+0

나는이 선생님을 이미했으나, ** localhost를 실행하려고 시도했을 때 연결을 거부했다 ** 오류가 발생한다. –

+0

다른 오류입니다 .. –

+0

그 오류를 해결하는 방법을 알고 계십니까 선생님? 고맙습니다. –

관련 문제