Search code examples
asp.net-mvchttp-redirectasp.net-mvc-partialviewasp.net-mvc-ajax

Contact Form Within Partial View


I have to admit, the transition from Web Forms to MVC is literally blowing my mind. I simply can not seem to wrap my head around how MVC functions as it compares to Web Forms, and I continue to hit roadblock after roadblock when trying to perform seemingly simple tasks. Couple this with a rudimentary knowledge of javascript/jquery, and I'm left scratching my head most days.

I have been working to transition a custom CMS that my company built from Web Forms to MVC. This CMS allows for the creation of pages and the manipulation of the site navigation, which resulted in the creation of a page model, along with related views and controllers.

While the client can edit 99% of the site, some elements are static and are loaded on demand on specific pages. For example, the Contact page exists within the CMS, but the site injects the actual contact form on demand.

When build in Web Forms, this contact form was simply a User Control, with its own logic for handing the postback. I thought the logical transition here would be the creation of a Partial View, but I have run into ridiculous amounts of difficulty in accomplishing this task. While I have been able to create the model, view and controller for this contact form, I simply can't seem to make it work correctly.

After literally 3 days of scouring Stack Overflow for advice, I completed nearly everything to make this work. However, I can't figure out how to perform a seemingly simple redirect from the Partial View to save my life. I have tried numerous approaches, including the one described at Doug.Instance, but haven't had any luck. Upon post, the partial view returns as an entire view, even though the controller uses 'return PartialView'. If I post it again, it returns as it originally displayed, as a partial view. In addition, my Redirect variable is not updating upon success, AND the OnSuccess javascript is not firing.

Below is my code. Please help me, because I'm running out of hair...

PAGE VIEW (SHORTENED FOR BREVITY)

...
@if (Model.ID == 8)
{
  //LOAD CONTACT FORM
  @Html.Action("Contact","ContactForm")
}...

CONTACT FORM PARTIAL VIEW (SHORTENED FOR BREVITY)

@model NCOWW.Models.ContactForm

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
  // Labels over the inputs.
  window.addEvent("load", function () {
    var myForm = document.id('contactForm');
    myForm.getElements('[type=text], textarea').each(function (el) {
      new OverText(el);
    });
  });
  function FormComplete() {
    if ($("#Redirect").val() != '') {
      document.location = $("#Redirect").val();
    } 
  } 
</script>
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "contactForm", OnSuccess = "FormComplete" }))
{
  @Html.ValidationSummary(true)
  <div id="contactForm">
    @Html.HiddenFor(model => model.Redirect)

    @Html.TextBoxFor(model => model.Name, new { tabindex = 1, @class = "half", Title = @Html.DisplayNameFor(model => model.Name) })
    @Html.ValidationMessageFor(model => model.Name)

       @Html.TextAreaFor(model => model.Comments, new { tabindex = 13, Title =     @Html.DisplayNameFor(model => model.Comments) })
    @Html.ValidationMessageFor(model => model.Comments)

    <br />
    <input type="submit" value="Submit" name="Submit" class="button" />
  </div>
}

CONTACT FORM CONTROLLER (SHORTENED FOR BREVITY)

public ActionResult Contact(ContactForm c)
    {
      try
      {
        MailMessage message = new MailMessage();
        message.IsBodyHtml = true;
        message.From = new MailAddress(c.Email);
        message.Body += "<b>Name:</b> " + c.FullName + "<br/><br/>";
        message.Body += "<b>Questions/Comments:</b><br> " + c.Comments;

        SmtpClient client = new SmtpClient();
        client.Send(message);
        c.Redirect = "/formsuccess";

        return PartialView("contactForm", c);
      }
      catch
      {
        return PartialView();
      }
    }

Solution

  • I was able to get this to work once I started rethinking about what I was actually trying to achieve. Instead of returning PartialView("contactForm", c);, I ended up returning Json(c);. I then parsed the returned Json and redirected from there. The final working code is as follows.

    PAGE VIEW (SHORTENED FOR BREVITY)

    ...
    @if (Model.ID == 8)
    {
      //LOAD CONTACT FORM
      @Html.Action("Contact","ContactForm")
    }...
    

    CONTACT FORM PARTIAL VIEW (SHORTENED FOR BREVITY)

    @model NCOWW.Models.ContactForm
    
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
      // Labels over the inputs.
      window.addEvent("load", function () {
        var myForm = document.id('contactForm');
        myForm.getElements('[type=text], textarea').each(function (el) {
          new OverText(el);
        });
      });
      function FormComplete(result) {
        if (result.Redirect != null && result.Redirect != '') {
          document.location = result.Redirect;
        }
      }
    </script>
    @using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "contactForm", OnSuccess = "FormComplete" }))
    {
      @Html.ValidationSummary(true)
      <div id="contactForm">
        @Html.HiddenFor(model => model.Redirect)
    
        @Html.TextBoxFor(model => model.Name, new { tabindex = 1, @class = "half", Title = @Html.DisplayNameFor(model => model.Name) })
        @Html.ValidationMessageFor(model => model.Name)
    
           @Html.TextAreaFor(model => model.Comments, new { tabindex = 13, Title =     @Html.DisplayNameFor(model => model.Comments) })
        @Html.ValidationMessageFor(model => model.Comments)
    
        <br />
        <input type="submit" value="Submit" name="Submit" class="button" />
      </div>
    }
    

    CONTACT FORM CONTROLLER (SHORTENED FOR BREVITY)

    public ActionResult Contact(ContactForm c)
    {
      try
      {
        MailMessage message = new MailMessage();
        message.IsBodyHtml = true;
        message.From = new MailAddress(c.Email);
        message.Body += "<b>Name:</b> " + c.FullName + "<br/><br/>";
        message.Body += "<b>Questions/Comments:</b><br> " + c.Comments;
    
        SmtpClient client = new SmtpClient();
        client.Send(message);
        c.Redirect = "/formsuccess";
    
        return Json(c);
      }
      catch
      {
        //ERROR CATCH CODE
      }
    }