0

我怀疑在 ASP.NET MVC 3 中完成了一个项目,其中有一个联系表。它完美地工作问题是我想发送一条消息“电子邮件发送成功!” 完成您的提交。我没有使用 Json。什么是最合适的解决方案 谢谢!

编码:

联系.cshtml `

@model SSInstitucional.ViewModel.ContatoViewModel
 @using System.Web     

<link href="../../Content/themes/SCTecno.css" rel="stylesheet" type="text/css" />

@using (Html.BeginForm("EnviaEmail")) 
{
    @Html.ValidationSummary(true, "")

    <div id ="divContato" style="text-align:left;  margin-left:460px; margin-right:400px; font-family:Verdana;">

            <div id="txtNome" class="editor-label">
                @Html.LabelFor(model => model.Nome)
               <p>
                @Html.TextBoxFor(m => m.Nome, new { id = "Nome", size = 40, maxlength = "60" })
                @Html.ValidationMessageFor(model => model.Nome)
            </div>
            <div id="txtEmail" class="editor-field">
                @Html.LabelFor(model => model.Email)
                <p>
                @Html.TextBoxFor(m => m.Email, new { id = "Email", size = 40, maxlength = "200" })
                @Html.ValidationMessageFor(model => model.Email)
            </div>
            <div  id="txtAssunto"class="editor-label">
               @Html.LabelFor(model => model.Assunto)
                <p>
                @Html.TextBoxFor(m => m.Assunto, new { id = "assunto", size = 40, maxlength = "200" })
                @Html.ValidationMessageFor(model => model.Assunto)
            </div>
            <div id="txtMensagem" class="editor-field">
               @Html.LabelFor(model => model.Mensagem)
               <p>
                @Html.TextAreaFor(model => model.Mensagem, new { id = "mensagem", rows = "10", cols = "50", maxlength = "5000" })
                @Html.ValidationMessageFor(model => model.Mensagem)
            </div>

                <div id="Enviar" onClick="alert('E-mail enviado com sucesso!!')")>
             @SSHtml.SubmitStyledButton("Enviar")
                </div>





   </div>
}

`

接触控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSInstitucional.ViewModel;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;


using System.Diagnostics;

namespace SSInstitucional.Controllers
{


    public class ContatoController : Controller
    {
        //
        // GET: /Contato/

        public ActionResult Index()
        {
            return View();
            Debug.WriteLine("Debug Teste");
        }

        [HttpPost]
        public ActionResult Index(ContatoViewModel contatoViewModel)
        {
            string corpo = "Nome: " + contatoViewModel.Nome + "\n" +
                               "E-Mail: " + contatoViewModel.Email + "\n" +
                               "Assunto: " + contatoViewModel.Assunto + "\n\n" +
                               contatoViewModel.Mensagem;

            sendEmail(contatoViewModel.Nome, contatoViewModel.Email, contatoViewModel.Assunto, corpo);

            // return Json ( new { Sucess = true, MessageBox = "Email enviado com sucesso!" });
            // return Json (new { mbox = "E-Mail enviado com sucesso!" });
            return View();

        }

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


        private void sendEmail(string fromName, string FromEmail, string subject, string body)
        {
            try
            {
                string smtpEmail = null;
                string usuarioEmail = null;
                string senhaEmail = null;
                int smtpPort = 0;
                bool enableSsl = false;

                MailMessage mail = new MailMessage();

                ////set the addresses
                mail.From = new MailAddress(FromEmail, fromName);
                mail.Sender = new MailAddress(FromEmail, fromName);
                mail.ReplyTo = new MailAddress(FromEmail, fromName);

                mail.To.Add(new MailAddress("myname@webmail.net", fromName));

                //set the content
                mail.Subject = subject;
                mail.Body = body;
                mail.Body += "\n\n------------------------------------------";
                mail.Body += "\n\nEmail de origem: " + FromEmail;
                mail.Body += "\n\n\nEmail enviado pelo Fale Conosco do site.";

                //send the message
                //SmtpClient smtp = new SmtpClient(smtpEmail);
                SmtpClient smtp = new SmtpClient("smtp.webmail.net");

                NetworkCredential credenciais = new NetworkCredential("contato@webmail.net", "sss1122");
                smtp.Credentials = credenciais;
                //smtp.Port = 587;
                if (smtpPort > 0)
                    smtp.Port = 25;

                // enable SSL
                if (enableSsl)
                    smtp.EnableSsl = true;

                smtp.Timeout = 120000;

                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                smtp.Send(mail);
                {
                    ModelState.Clear();
                    //return mail(new { Message = "E-mail enviado com sucesso!" });
                }

            }
            catch (FormatException erroFormato)
            {
                throw new Exception("Falha ao enviar email. Verifique se seu email foi digitado corretamente.");
            }
            catch (Exception erro)
            {
                throw new Exception("Falha ao enviar email.");


            }
        }



    }

}
4

2 回答 2

2

如果可以使用 js,则可以使用 MVC Ajax 表单。一个例子在这里http://www.hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx

你只需要更换

@using (Html.BeginForm("EnviaEmail")) 
{
   ....
}

@using(Ajax.BeginForm("EnviaEmail", new AjaxOptions
                                                      {
                                                              UpdateTargetId = "form_wrapper_id",
                                                              InsertionMode = InsertionMode.Replace
                                                      }))
{
    ...
}

并从Action返回一些按摩。此消息将被放入 ID 为“form_wrapper_id”的 HTML 标记中。如果您不能使用 js,Darin Dimitrov 的答案是最好的。

于 2012-04-17T05:19:18.700 回答
0

您的表单当前指向EnviaEmail控制器操作。EnviaEmail控制器动作不做任何事情。它只会重新显示视图。它不发送任何电子邮件。所以我猜你的原始代码实际上是指向 Index POST 操作:

@using (Html.BeginForm())
{
    ...    
}

从我在您的代码中可以看到,此 POST 操作会发送一封电子邮件并重新显示相同的视图。因此,一旦发送了电子邮件,您就可以在 ViewBag 中存储一些消息:

[HttpPost]
public ActionResult Index(ContatoViewModel contatoViewModel)
{
    string corpo = "Nome: " + contatoViewModel.Nome + "\n" +
                       "E-Mail: " + contatoViewModel.Email + "\n" +
                       "Assunto: " + contatoViewModel.Assunto + "\n\n" +
                       contatoViewModel.Mensagem;

    sendEmail(contatoViewModel.Nome, contatoViewModel.Email, contatoViewModel.Assunto, corpo);

    ViewBag.Message = "Email sent successfully";
    return View();
}

然后在您的视图中显示此消息:

<div>@ViewBag.Message</div>
于 2012-04-16T21:02:26.267 回答