C# 在ASP.NET MVC中附加多个文件

C# 在ASP.NET MVC中附加多个文件,c#,asp.net-mvc,file-upload,asp.net-mvc-5,email-attachments,C#,Asp.net Mvc,File Upload,Asp.net Mvc 5,Email Attachments,我一直在尝试在我制作的网站中附加/上传多个文件。正在发送姓名、电子邮件、主题和消息,但消息中没有附件。这些文件似乎不在uploads文件夹中。我真的不知道怎么了。请帮帮我。我对这种东西不熟悉。非常感谢。以下是我的看法: @using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken()

我一直在尝试在我制作的网站中附加/上传多个文件。正在发送姓名、电子邮件、主题和消息,但消息中没有附件。这些文件似乎不在uploads文件夹中。我真的不知道怎么了。请帮帮我。我对这种东西不熟悉。非常感谢。以下是我的看法:

@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>
}
@使用(Html.BeginForm(“Index”,“Home”,null,FormMethod.Post,new{enctype=“multipart/formdata”}))
{
@Html.AntiForgeryToken()
@LabelFor(m=>m.FromName)
@TextBoxFor(m=>m.FromName,新的{@class=“form control”})
@Html.ValidationMessageFor(m=>m.FromName)
@LabelFor(m=>m.FromEmail)
@TextBoxFor(m=>m.FromEmail,新的{@class=“form control”})
@Html.ValidationMessageFor(m=>m.FromEmail)
@LabelFor(m=>m.FromSubject)
@TextBoxFor(m=>m.FromSubject,新的{@class=“form control”})
@Html.ValidationMessageFor(m=>m.FromSubject)
@使用(Html.BeginForm(“Multiple”、“Home”、FormMethod.Post、new{enctype=“multipart/formdata”}))
{



} @LabelFor(m=>m.Message) @text区域(m=>m.Message,新的{@class=“form control”}) @Html.ValidationMessageFor(m=>m.Message) @if((TempData[“recaptcha”])!=null) { @TempData[“recaptcha”]

} }
这是我的控制器:

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();
}
public ActionResult Index()
{
返回视图();
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务索引(EmailFormModel)
{
if(ModelState.IsValid)
{
字符串EncodedResponse=Request.Form[“g-Recaptcha-Response”];
bool IsCaptchaValid=(ReCaptcha.Validate(EncodedResponse)=“真”?真:假);
if(IsCaptchaValid)
{
var body=“电子邮件发件人:{0}({1})

消息:

{2}

”; var message=new MailMessage(); message.To.Add(新邮件地址(“***@gmail.com”);//替换为有效值 message.From=新邮件地址(“***@ymailcom”);//替换为有效值 message.Subject=“您的电子邮件主题”; message.Body=string.Format(Body,model.FromName,model.FromEmail,model.FromSubject,model.message); message.IsBodyHtml=true; 使用(var smtp=new SmtpClient()) { var-credential=新网络凭据 { UserName=“***@gmail.com”,//替换为有效值 Password=“***”//替换为有效值 }; smtp.Credentials=凭证; smtp.Host=“smtp.gmail.com”; smtp.Port=587; smtp.EnableSsl=true; 等待smtp.SendMailAsync(消息); //返回重定向操作(“已发送”); ViewBag.Message=“您的邮件已发送!”; //TempData[“message”]=“message sent”; ModelState.Clear(); 返回视图(“索引”); } }否则 { TempData[“recaptcha”]=“请确认您不是机器人!”; } } 返回视图(模型); } [HttpPost] public ActionResult多个(IEnumerable文件) { foreach(文件中的var文件) { 如果(file!=null&&file.ContentLength>0) { file.SaveAs(Path.Combine(Server.MapPath(“/uploads”)、Guid.NewGuid()+Path.GetExtension(file.FileName)); } } 返回视图(); }
您的第一行代码就是问题所在

Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data"
这是对家庭控制器索引的后期操作。无法发布另一个HttpPost,操作本身需要一个HttpPost,正如您可以从ActionResult名称上方的数据注释中看到的那样


为什么要使用嵌套表单

视图不应包含嵌套表单提交。所以把它减少到一个,同样可以用来上传文件

@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>
}
@使用(Html.BeginForm(“Index”,“Home”,null,FormMethod.Post,new{enctype=“multipart/formdata”}))
{
@Html.AntiForgeryToken()
@LabelFor(m=>m.FromName)
@TextBoxFor(m=>m.FromName,新的{@class=“form control”})
@Html.ValidationMessageFor(m=>m.FromName)
@LabelFor(m=>m.FromEmail)
@TextBoxFor(m=>m.FromEmail,新的{@class=“form control”})
@Html.ValidationMessageFor(m=>m.FromEmail)
@LabelFor(m=>m.FromSubject)
@TextBoxFor(m=>m.FromSubject,新的{@class=“form control”})
@Html.ValidationMessageFor(m=>m.FromSubject)
{


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);

}