Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Phillip Turner 98 posts 412 karma points
    Apr 26, 2014 @ 06:10
    Phillip Turner
    1

    TempData not persisting from Controller to View Umbraco 6.1.6 MVC

    Hello All.

    I am trying to return a success / fail message to my view using TempData, but TempData is always null once returned to the view. On a side note, in desperation, I also tried ViewData and even tried to use Session variables, but they failed as well. Am i missing something?

    Here is my Controller Code:

        [HttpPost]
        [RecaptchaControlMvc.CaptchaValidator]
        public ActionResult SubmitContactFormAction(Models.MlsContactFormModel model, bool captchaValid, string captchaErrorMessage)
        {
            // Clear the temp data
            //TempData["submit-status"] = null;
            //Session["submit-status"] = null;
    
            if (!captchaValid)
            {
                ModelState.AddModelError("captcha-error", captchaErrorMessage);
                return CurrentUmbracoPage();
            }
            else
            {
                string smtp = "internalopenrelay.mydomain.com";
                Document cSettings = new Document(3354);
                string emailFrom = cSettings.getProperty("fromAddressMainContact").Value.ToString();
                string emailTo = cSettings.getProperty("mainContactRecipient").Value.ToString();
                string messageTemplate = cSettings.getProperty("mainMessageTemplate").Value.ToString();
    
                if (ModelState.IsValid)
                {
                    string _name = model.Name;
                    string _email = model.Email;
                    string _phone = model.Phone;
                    string _subject = model.Subject;
                    string _message = model.Message;
                    bool _sendcopy = model.SendCopy;
                    string[] messageVariables = { "{{NAME}}", "{{EMAIL}}", "{{PHONE}}", "{{SUBJECT}}", "{{MESSAGE}}" };
                    string[] modelVaribles = { _name, _email, _phone, _subject, _message };
    
                    for (var i = 0; i < messageVariables.Length; i++)
                        messageTemplate = messageTemplate.Replace(messageVariables[i], modelVaribles[i]);
    
                    SmtpClient SMTPClient = new SmtpClient(smtp);
                    MailAddress FromAddress = new MailAddress(emailFrom);
                    MailAddress ToAddress = new MailAddress(emailTo);
                    MailMessage Message = new MailMessage(FromAddress, ToAddress);
                    Message.Body = messageTemplate;
                    Message.Subject = "New Website Contact Request";
                    Message.IsBodyHtml = true;
    
                    try
                    {
                        //SMTPClient.Send(Message);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
    
                    SMTPClient.Dispose();
                    TempData["submit-status"] = "Request send successfully";
                    //TempData.Keep("submit-status");
                    ModelState.Clear();
                    //Session["frmStatus"] = "Success";
                    return CurrentUmbracoPage();
                }
                else
                {
                    TempData["submit-status"] = "There was an error while sending the request";
                    //TempData.Keep("submit-status");
                    ///Session["frmStatus"] = "Failed";
                    return CurrentUmbracoPage();
                }
            }
    

    Here is my view:

    @model WebStaging1.Models.MlsContactFormModel
    @using Recaptcha
    @using (Html.BeginUmbracoForm("SubmitContactFormAction", "MlsContactForm"))
    {
    @Html.ValidationSummary(true)
    <div>
        Fields marked with * are required<br/><br />
        <div class="clear pad-5">
            <div class="label-column">
            @Html.LabelFor(model => model.Name) * 
            </div>
            <div class="input-column">
            @Html.TextBoxFor(model => model.Name, new { @class = "input-242" })<br />
            @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>
        <div class="clear pad-5">
            <div class="label-column">
            @Html.LabelFor(model => model.Email) * 
            </div>
            <div class="input-column">
            @Html.TextBoxFor(model => model.Email, new { @class = "input-242" })<br />
            @Html.ValidationMessageFor(model => model.Email)
            </div>
        </div>
        <div class="clear pad-5">
            <div class="label-column">
            @Html.LabelFor(model => model.Phone) 
            </div>
            <div class="input-column">
            @Html.TextBoxFor(model => model.Phone, new { @class = "input-242" })
            </div>
        </div>
        <div class="clear pad-5">
            <div class="label-column">
            @Html.LabelFor(model => model.Subject) * 
            </div>
            <div class="input-column">
            @Html.TextBoxFor(model => model.Subject, new { @class = "input-242" })
                <br />
            @Html.ValidationMessageFor(model => model.Subject)
            </div>
        </div>
        <div class="clear pad-5">
            <div class="label-column">
            @Html.LabelFor(model => model.Message) * 
            </div>
            <div class="input-column">
            @Html.TextAreaFor(model => model.Message, new { @class = "input-textarea" })<br />
            @Html.ValidationMessageFor(model => model.Message)
            </div>
        </div>
        <br />
        <div id="captcha-panel" class="clear" style="text-align: right; float: right; padding-top: 5px;">
            @Html.Raw(Html.GenerateCaptcha("captcha", "custom"))
        </div>
        <p>
        <div id="captcha-result" class="clear">
            @Html.ValidationMessage("captcha-error")
            @(TempData["submit-status"] != null ? TempData["submit-status"].ToString() : "")
        </div>
        <div class="clear pad-5" style="float: right; text-align: center;">
            <button type="submit">Send</button><br />  
        </div>
    </div>
    }
    
  • Shannon Deminick 1524 posts 5269 karma points MVP 2x
    May 01, 2014 @ 07:01
    Shannon Deminick
    2

    Hi Phillip,

    Generally speaking when a form is successful you would redirect (this prevents people from resubmitting the form accidentally with a page refresh), when it contains errors you do not redirect. I'm sure you've read through the docs here: http://our.umbraco.org/documentation/Reference/Templating/Mvc/forms.

    When you redirect then ViewData/ViewBag is not persisted whereas TempData is persisted - this is actually the entire point of TempData, to persist after a single redirect.

    In your controller above:

    This is correct:

        if (!captchaValid)
        {
            ModelState.AddModelError("captcha-error", captchaErrorMessage);
            return CurrentUmbracoPage();
        }
    

    When ModelState.IsValid, you'd want to redirect and use TempData:

            if (ModelState.IsValid)
            {
               ...
               TempData["submit-status"] = "Request send successfully";
               return RedirectToCurrentUmbracoPage(); 
            }
    

    When ModelState is not valid, you'd want to not redirect and use ViewData/ViewBag. Though since ModelState is already invalid you'll already have model state errors so adding yet another error message may not be necessary:

            else
            {
                ViewData["submit-status"] = "There was an error while sending the request";
                return CurrentUmbracoPage();
            }
    

    If you do not want to redirect on success because you want to keep ModelState then you can do this instead:

            if (ModelState.IsValid)
            {
               ....
    
               //TempData should also persist without a redirect too but generally TempData is only used
               // for redirect purposes.
               ViewData["submit-status"] = "Request send successfully";
               return CurrentUmbracoPage(); 
            }
    
Please Sign in or register to post replies

Write your reply to:

Draft