2016-05-11 21 views
-1

私が作っているウェブサイトに複数のファイルを添付/アップロードしようとしました。名前、電子メール、件名&メッセージは送信されていますが、メッセージに添付ファイルはありません。ファイルがアップロードフォルダにないと思われます。私は本当に何が間違っているのか分からない。私を助けてください。私はこの種のもので新しいです。ありがとうございました。ここに私の見解です:ASP.NET MVCで複数のファイルを添付

@using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.AntiForgeryToken() 
    <div class="col-md-4"> 
     <div class="contact_form block"> 
      <div class="row"> 
       <div class="col-md-12 col-sm-12"> 
        <div id="note"></div> 
       </div> 
      </div> 
      <div id="fields"> 

       <div class="col-md-12 col-sm-6"> 
        @Html.LabelFor(m => m.FromName) 
        @Html.TextBoxFor(m => m.FromName, new { @class = "form-control" }) 
        @Html.ValidationMessageFor(m => m.FromName) 
       </div> 
       <div class="col-md-12 col-sm-6"> 
        @Html.LabelFor(m => m.FromEmail) 
        @Html.TextBoxFor(m => m.FromEmail, new { @class = "form-control" }) 
        @Html.ValidationMessageFor(m => m.FromEmail) 
       </div> 
       <div class="clear"></div> 
       <div class="col-md-12 col-sm-6"> 
        @Html.LabelFor(m => m.FromSubject) 
        @Html.TextBoxFor(m => m.FromSubject, new { @class = "form-control" }) 
        @Html.ValidationMessageFor(m => m.FromSubject) 
       </div> 
       <div class="col-md-12"> 
       @using (Html.BeginForm("Multiple", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
       { 
        <div id="multiple"> 
         <input type="file" class="multiple" name="files" multiple /> 
        </div> 
        <div id="single"> 
         <input type="file" class="single" name="files" /><br /> 
         <input type="file" class="single" name="files" /><br /> 
         <input type="file" class="single" name="files" /><br /> 
        </div> 

       } 
       </div> 
       <div class="col-md-12"> 
        @Html.LabelFor(m => m.Message) 
        @Html.TextAreaFor(m => m.Message, new { @class = "form-control" }) 
        @Html.ValidationMessageFor(m => m.Message) 
       </div> 
       <div class="col-md-12">     
        <div> 
         @if ((TempData["recaptcha"]) != null) 
         { 
          <p>@TempData["recaptcha"]</p> 
         } 
        </div> 
        <div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div> 
       </div> 

       <div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div> 

      </div> 
     </div> 
    </div> 
} 

そして、ここでは私のコントローラだ:コードの

public ActionResult Index() 
{ 
    return View(); 
} 

[HttpPost] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Index(EmailFormModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     string EncodedResponse = Request.Form["g-Recaptcha-Response"]; 
     bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false); 
     if(IsCaptchaValid) 
     { 

      var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>"; 
      var message = new MailMessage(); 
      message.To.Add(new MailAddress("***@gmail.com")); // replace with valid value 
      message.From = new MailAddress("***@ymailcom"); // replace with valid value 
      message.Subject = "Your email subject"; 
      message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message); 
      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; 
       await smtp.SendMailAsync(message); 
       //return RedirectToAction("Sent"); 
       ViewBag.Message = "Your message has been sent!"; 

       //TempData["message"] = "Message sent"; 
       ModelState.Clear(); 
       return View("Index"); 
      } 

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

[HttpPost] 
public ActionResult Multiple(IEnumerable<HttpPostedFileBase> files) 
{ 
    foreach (var file in files) 
    { 
     if (file != null && file.ContentLength > 0) 
     { 
      file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName))); 
     } 
    } 
    return View(); 
} 
+0

ネストされたフォームは無効なhtmlであり、サポートされていません( 'Multiple()'メソッドにヒットしません)。内側のフォーム要素を削除し、 'IEnumerable files'パラメータを含むように' Index() 'を変更するか、2つの別個のメソッドを必要とする場合は内側のフォームを外側のフォームの後に移動してください。 –

+0

htmlでネストされたフォームはサポートされません。これが問題の原因になっている可能性があります。 –

+0

ご協力いただきありがとうございます。今は大丈夫です。ファイルは「アップロード」フォルダに入っていますが、それでも電子メールには届きません。助けていただければ幸いです。 –

答えて

0

あなたの最初の行が問題です。

Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" 

これは、ホームコントローラの[インデックス]へのポストアクションです。別のHttpPostをHttpPostすることはできませんが、ActionResult名の上にあるデータ注釈でわかるように、アクション自体はHttpPostを期待しています

なぜネストされたフォームを使用しますか?

0

あなたのビューには、ネストされたフォームの投稿が含まれてはいけません。それを1つに減らし、同じものをファイルのアップロードに使うことができます。

@using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
@Html.AntiForgeryToken() 
<div class="col-md-4"> 
    <div class="contact_form block"> 
     <div class="row"> 
      <div class="col-md-12 col-sm-12"> 
       <div id="note"></div> 
      </div> 
     </div> 
     <div id="fields"> 

      <div class="col-md-12 col-sm-6"> 
       @Html.LabelFor(m => m.FromName) 
       @Html.TextBoxFor(m => m.FromName, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(m => m.FromName) 
      </div> 
      <div class="col-md-12 col-sm-6"> 
       @Html.LabelFor(m => m.FromEmail) 
       @Html.TextBoxFor(m => m.FromEmail, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(m => m.FromEmail) 
      </div> 
      <div class="clear"></div> 
      <div class="col-md-12 col-sm-6"> 
       @Html.LabelFor(m => m.FromSubject) 
       @Html.TextBoxFor(m => m.FromSubject, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(m => m.FromSubject) 
      </div> 
      <div class="col-md-12"> 
      { 
       <div id="multiple"> 
        <input type="file" class="multiple" name="files" multiple /> 
       </div> 
       <div id="single"> 
        <input type="file" class="single" name="files" /><br /> 
        <input type="file" class="single" name="files" /><br /> 
        <input type="file" class="single" name="files" /><br /> 
       </div> 


      </div> 
      <div class="col-md-12"> 
       @Html.LabelFor(m => m.Message) 
       @Html.TextAreaFor(m => m.Message, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(m => m.Message) 
      </div> 
      <div class="col-md-12">     
       <div> 
        @if ((TempData["recaptcha"]) != null) 
        { 
         <p>@TempData["recaptcha"]</p> 
        } 
       </div> 
       <div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div> 
      </div> 

      <div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div> 

     </div> 
    </div> 
</div> 
} 

さらに、アクションにパラメータを追加して、クライアント要求からファイルを受け取り、同じアクションで処理します。

public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files) 
{ 
if (ModelState.IsValid) 
    { 
     //logic here upload file logic here. 
     foreach (var file in files) 
     { 
      if (file != null && file.ContentLength > 0) 
      { 
       file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.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>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>"; 
      var message = new MailMessage(); 
      message.To.Add(new MailAddress("***@gmail.com")); // replace with valid value 
      message.From = new MailAddress("***@ymailcom"); // replace with valid value 
      message.Subject = "Your email subject"; 
      message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message); 
      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; 
       await smtp.SendMailAsync(message); 
       //return RedirectToAction("Sent"); 
       ViewBag.Message = "Your message has been sent!"; 

       //TempData["message"] = "Message sent"; 
       ModelState.Clear(); 
       return View("Index"); 
      } 

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

} 
+0

ご協力いただきありがとうございます。ファイルは「アップロード」フォルダに入っていますが、それでも電子メールには届きません。あなたの助けが大変ありがとうございます。 –

+0

@KenHemmo - このファイルをメールに添付するには、一時的にサーバーに保存してメールに添付してから処分できます。それがうまくいくことを願っています。 –

+0

私はこれをやろうとします。それがうまくいけば更新してください。何か間違っていたら何か質問をしてくれることを願っています。ご協力いただきありがとうございます。 –

関連する問題