Heidel
Heidel

Reputation: 3254

Show message “Email sending failed/successful” asp.net mvc 4 via ViewBag

I have feedback form on my mvc site and I send this form to email.
I'd like to show error message in case email sending is failed and success message in case email sending is successful. I try to make that via ViewBag.
I added in my controller

    [HttpGet]
    public ActionResult Feedback(string Message)
    {
        if (Message != null)
        {
            if (Message == "No")
            {
                ViewBag.Message = "Error";
            }

            if (Message == "Yes")
            {
                ViewBag.Message = "Success";
            }
        }

        else
        {
            ViewBag.Message = null;
        }

        return View();
    }

    [HttpPost]
    public ActionResult Feedback(FeedbackForm Model)
    {
        string Message;

        //email
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.BodyEncoding = Encoding.UTF8;
        msg.Priority = MailPriority.High;

        msg.From = new MailAddress(Model.Email, Model.Name);
        msg.To.Add(/*"[email protected]"*/"[email protected]");

        msg.Subject = @Resources.Global.Feedback_Email_Title + " " + Model.Company;
        string message = @Resources.Global.Feedback_Email_From + ": " + Model.Name + "\n"
                        + @Resources.Global.Feedback_Email + ": " + Model.Email + "\n"
                        + @Resources.Global.Feedback_Phone + ": " + Model.Phone + "\n"
                        + @Resources.Global.Feedback_Company + ": " +  Model.Company + "\n\n"
                        + Model.AdditionalInformation;
        msg.Body = message;
        msg.IsBodyHtml = false;

        //Attachment
        if (Model.ProjectInformation != null && !(String.IsNullOrEmpty(Model.ProjectInformation.FileName)))
        {
            HttpPostedFileBase attFile = Model.ProjectInformation;
            if (attFile.ContentLength > 0)
            {
                var attach = new Attachment(attFile.InputStream, attFile.FileName);
                msg.Attachments.Add(attach);
            }
        }

        SmtpClient client = new SmtpClient("denver.corepartners.local", 55);
        client.UseDefaultCredentials = false;
        client.EnableSsl = false;

        try
        {
            client.Send(msg);
            return RedirectToAction("Feedback", "Home", Message = "Yes");
        }

        catch (Exception ex)
        {
            return RedirectToAction("Feedback", "Home", Message = "No");
        }
    }

and I added in my view

    @if (ViewBag.Message != null)
    {
        <p style="color: red;">@ViewBag.Message</p>
    }

but I don't get any message in any case.
What's wrong?

Upvotes: 1

Views: 5198

Answers (1)

Colm Prunty
Colm Prunty

Reputation: 1620

Try this:

return RedirectToAction("Feedback", "Home", new { Message = "Yes" });

Upvotes: 3

Related Questions