Copied to clipboard

Flag this post as spam?

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


  • Dan Sørensen 102 posts 327 karma points
    Jan 09, 2014 @ 15:02
    Dan Sørensen
    0

    Updatepanel in mvc how to get content with a ajax call

    Hello umbraco users I need help with something and hope you can help.
    I want to get content async so the hole page dosent refresh. 

    I have listed some news and now I want to show the content of the news on the same page maybe with a ajax call and some javascript to fade it in but im not sure where to start, maybe you can just point me in a direction. 
    Im pretty new to umbraco and mvc I normaly just used the updatepanel in the webforms to achieve this.

  • Andy Butland 422 posts 2334 karma points MVP 4x hq c-trib
    Jan 09, 2014 @ 20:50
    Andy Butland
    0

    Hi Dan

    You should probably first check out the jquery library and it's AJAX functions if you aren't familiar with that.  You can use that to make a call to a URL in JavaScript to retrieve either some HTML or JSON that you can then format to display.  The URL can be a surface controller set to return a partial view or JSON result, or you could look at the Umbraco Web API controller to return your data.

    Here's some documentation links:

    http://our.umbraco.org/documentation/Reference/Templating/Mvc/surface-controllers

    http://our.umbraco.org/documentation/Reference/WebApi/

    Hope that helps get you started.

    Andy

  • Yasir Butt 161 posts 371 karma points
    Jan 09, 2014 @ 22:48
    Yasir Butt
    1

    Hi Dan!

    Here is my contact us form code. Hope it will help you

    This is controller 

    [HttpPost]

            public ActionResult ContactUsSubmit(ContactUsModel contactus)

            {

                if (ModelState.IsValid == false)

                {

                    //return PartialView("~/Views/Partials/GiveMeOffer.cshtml", offer);

                    return Json(new { success = false });

                }

     

                var node = uQuery.GetNode(contactus.NodeId);

     

                var root = uQuery.GetNodesByType("HomePage").FirstOrDefault();

                

                var emailSubject = node.GetProperty("emailSubject").Value;

                var fromEmail = root.GetProperty("systemEmail").Value;

                var toEmail = node.GetProperty("toEmail").Value;

                var emailTemplate = node.GetProperty("emailBody").Value.Replace("##phone##", contactus.CustomerPhone);

                emailTemplate = emailTemplate.Replace("##name##", contactus.CustomerEmail);

                emailTemplate = emailTemplate.Replace("##email##", contactus.CustomerEmail);

                emailTemplate = emailTemplate.Replace("##message##", contactus.CustomerMessage);

     

                var emailUtil = new Utilities();

                emailUtil.SendEmail(emailSubject, fromEmail, toEmail, emailTemplate);

                //if (contactus.SendCopytoCustomer != null && (bool)offer.SendCopytoCustomer)

                //    emailUtil.SendEmail(emailSubject, fromEmail, offer.CustomerEmail, emailTemplate);

     

                return Json(new { success = true });

            }

     

    It is Model

    public class ContactUsModel

        {

            [Required(ErrorMessage = "Navn må oppgis.")]

            public string CustomerName { get; set; }

     

            [Required(ErrorMessage = "Mobil må oppgis.")]

            [RegularExpression("^[0-9]+$", ErrorMessage = "Mobil må være nummer.")]

            [MinLength(8, ErrorMessage = "Mobil må være 8 tall.")]

            [Phone(ErrorMessage = "Mobil må oppgis")]

            public string CustomerPhone { get; set; }

     

            [Required(ErrorMessage = "E-post må oppgis.")]

            [EmailAddress(ErrorMessage = "Ugyldy e-post.")]

            public string CustomerEmail { get; set; }

     

            [Required(ErrorMessage = "Melding må oppgis.")]

            [MaxLength(ErrorMessage = "Melding må være under 500.")]

            public string CustomerMessage { get; set; }

     

            public int NodeId { get; set; }

        } 

     

    Here is partial view

    @model client.Models.ContactUsModel

     

    @using (Ajax.BeginForm("ContactUsSubmit", "ContactUsSurface", new AjaxOptions

     {

         HttpMethod = "POST",

         InsertionMode = InsertionMode.Replace,

         UpdateTargetId = "callMeResult",

         OnFailure = "ShowError()",

         OnSuccess = "ShowSuccess(data)",

     }))

    {

         

        <div class="success" style="display: none;">Vi kontakter deg snart!</div>

     

        <div class="errormessage" style="display: none;">Det er noe feil oppset! Prøv senere.</div>

     

        <div class="clearfix step2form">

            <div class="step2left contactform">

                

     

                <div data-error="validationBox" class="textRow">

                    <div class="rowLabel">

                        <label for="CustomerName">Navn</label>

                        @Html.ValidationMessageFor(model => model.CustomerName)

                    </div>

                    @Html.TextBoxFor(model => model.CustomerName, new { maxLength = 50, autocomplete = "off", placeholder = "Navn",@class ="uniform text" })

                </div>

                

                <div data-error="validationBox" class="textRow">

                    <div class="rowLabel">

                        <label for="CustomerEmail">E-post</label>

                        @Html.ValidationMessageFor(model => model.CustomerEmail)

                    </div>

                    @Html.TextBoxFor(model => model.CustomerEmail, new { maxLength = 50, autocomplete = "off", placeholder = "E-post",@class ="uniform text" })

                </div>

                

                <div data-error="validationBox" class="textRow">

                    <div class="rowLabel">

                        <label for="CustomerPhone">Mobil</label>

                        @Html.ValidationMessageFor(model => model.CustomerPhone)

                    </div>

                    @Html.TextBoxFor(model => model.CustomerPhone, new { maxLength = 50, autocomplete = "off", placeholder = "Mobil",@class ="uniform text" })

                </div>

                

                <div data-error="validationBox" class="textRow">

                    <div class="rowLabel">

                        <label for="CustomerMessage">Melding</label>

                        @Html.ValidationMessageFor(model => model.CustomerMessage)

                    </div>

                    @Html.TextAreaFor(model => model.CustomerMessage, new { placeholder = "Melding",@class ="uniform text" ,cols="38", rows="5" })

                </div>

                

                 <div class="clearfix">

                 <a class="button2 p19" onclick="Reset();">reset</a>

                <input id="callmeSubmit" type="submit" class="button2" value="Send">

                @Html.HiddenFor(model => model.NodeId)

            </div>

            </div>

           

        </div>

        

     }

     

    <script>

        function ShowError() {

            $(".errormessage").show();

        }

     

        function ShowSuccess(data) {

            if (data.success) {

                $(".success").show();

                ClearField();

            } else {

                ShowError();

            }

        }

     

        function Reset() {

            ClearField();

            $(".success").hide();

            $(".errormessage").hide();

        }

     

        function ClearField() {

            $(".contactform #CustomerName").val("");

            $(".contactform #CustomerPhone").val("");

            $(".contactform #CustomerEmail").val("");

            $(".contactform #CustomerMessage").val("");

        }

    </script>

     

    This is partial view call in a regular view

     @Html.Partial("~/Views/Partials/ContactUsForm.cshtml", new Client.Models.ContactUsModel())

     

    But you can improve it if you want to e.g use content servive instead og uquery.

     

    Hope this will help you

  • Phillip Turner 98 posts 412 karma points
    Apr 16, 2014 @ 21:15
    Phillip Turner
    1

    Hey Yasir (or anyone!!!).

    I followed this tutorial: Ajax Umbraco MVC forms Guide

    My code works before the ajax implementation.

    After the small modifications, my code is very similar to yours. Ajax returns a success response but the controller breakpoint is never hit and so no email is ever sent

    I am on 6.1.6 but the code is the same. Any ideas?

    Here is my code:

    Controller:

    public class QuickContactController : SurfaceController
    {
        public ActionResult Index()
        {
            return PartialView("~/Views/Partials/mes-mini-contact.cshtml", new QuickContactModel());
        }
    
        [HttpPost]
        public ActionResult MESQuickContactPost(Models.QuickContactModel model)
        {
            string smtp = "internalopenrelay.xxxxx.com";
            Document cSettings = new Document(1303);
            string from = cSettings.getProperty("fromAddress").Value.ToString();
    
            if (!ModelState.IsValid)
            {
                //return CurrentUmbracoPage();
                return Json(new { sucess = false });
            }
    
            string _name = model.Name;
            string _email = model.Email;
            string _messsage = model.Message;
    
            SmtpClient SMTPClient = new SmtpClient(smtp);
            MailAddress FromAddress = new MailAddress(from);
            MailAddress ToAddress = new MailAddress("[email protected]");
            MailMessage Message = new MailMessage(FromAddress, ToAddress);
            Message.Body = string.Format("New message from: {0}<br>Email Address: {1}<p>{2}</p>", _name, _email, _messsage);
            Message.Subject = "New MES Quick Contact Message";
            Message.IsBodyHtml = true; ;
            try
            {
                SMTPClient.Send(Message);
            }
            catch (Exception)
            {
                throw;
            }
    
            SMTPClient.Dispose();
    
            //return RedirectToCurrentUmbracoPage();
            return Json(new { success = true });
        }
    }
    

    Model:

    public class QuickContactModel
    {
        [Required]
        public string Name { get; set; }
    
        [Required]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
    
        [Required]
        public string Message { get; set; }
    }
    

    Partial View:

    @model UmbracoUsStaging1.Models.QuickContactModel
    @using (Ajax.BeginForm("MESQuickContactPost", "QuickContactController", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "submit-status", OnFailure = "ShowError()", OnSuccess = "ShowSuccess()"}))
    {
    @Html.ValidationSummary(true)
    <span class="form-required">@Html.ValidationMessageFor(model => model.Name)</span><br />
    @Html.TextBoxFor(model => model.Name, new { @class = "flat-input width174", placeholder = "Name" })<br />    
    <span class="form-required">@Html.ValidationMessageFor(model => model.Email)</span><br />
    @Html.TextBoxFor(model => model.Email, new { @class = "flat-input width174", placeholder = "Email" })<br />
    <span class="form-required">@Html.ValidationMessageFor(model => model.Message)</span><br />
    @Html.TextAreaFor(model => model.Message, new { @class = "flat-input width174 height85", placeholder = "Message" })<br />
    <br />
    <a href="javascript:$('form').submit();" class="button-send">Send</a>
    <div id="submit-status"></div>
    <script>
        function ShowError() {
            $("#submit-status").html("Oops, there was an Error")
        }
    
        function ShowSuccess() {
            $("#submit-status").html("Message sent successfully");
            $("#Name").val("");
            $("#Email").val("");
            $("#Message").val("");
        }
    </script>
    }
    
  • Yasir Butt 161 posts 371 karma points
    Apr 16, 2014 @ 21:30
    Yasir Butt
    0

    Hi Philip

    Can you please submit the form with input type submit rather than using a tag and jquery? 

    e.g  <inputtype="submit"value="Send"> OR <button type="submit">Send</button>

    Please let me know if it helps

    Yasir

  • Phillip Turner 98 posts 412 karma points
    Apr 16, 2014 @ 21:34
    Phillip Turner
    0

    Funny I was just doing that when I saw your reply. Unfortunately, its the same result

    @model UmbracoUsStaging1.Models.QuickContactModel
    @using (Ajax.BeginForm("MESQuickContactPost", "QuickContactController", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "submit-status", OnFailure = "ShowError()", OnSuccess = "ShowSuccess()"}))
    {
    @Html.ValidationSummary(true)
    <span class="form-required">@Html.ValidationMessageFor(model => model.Name)</span><br />
    @Html.TextBoxFor(model => model.Name, new { @class = "flat-input width174", placeholder = "Name" })<br />    
    <span class="form-required">@Html.ValidationMessageFor(model => model.Email)</span><br />
    @Html.TextBoxFor(model => model.Email, new { @class = "flat-input width174", placeholder = "Email" })<br />
    <span class="form-required">@Html.ValidationMessageFor(model => model.Message)</span><br />
    @Html.TextAreaFor(model => model.Message, new { @class = "flat-input width174 height85", placeholder = "Message" })<br />
    <br />
    <button type="submit">Send</button>
    <!--<a href="javascript:$('form').submit();" class="button-send">Send</a>-->
    <div id="submit-status"></div>
    <script>
        function ShowError() {
            $("#submit-status").html("Oops, there was an Error")
        }
    
        function ShowSuccess() {
            $("#submit-status").html("Message sent successfully");
            $("#Name").val("");
            $("#Email").val("");
            $("#Message").val("");
        }
    </script>
    }
    
  • Yasir Butt 161 posts 371 karma points
    Apr 16, 2014 @ 21:37
    Yasir Butt
    0

    are you getting any error or activity in your browser console?

  • Phillip Turner 98 posts 412 karma points
    Apr 16, 2014 @ 21:44
    Phillip Turner
    0

    No errors and OnSuccess is triggered and my ShowSuccess js method is executed.

  • Phillip Turner 98 posts 412 karma points
    Apr 16, 2014 @ 21:46
    Phillip Turner
    0

    Not that this should matter (but it may) this partial view renders on another partial view as follows:

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    @using UmbracoUsStaging1.Controllers
    @using UmbracoUsStaging1.Models
    
    @{
    var footer = Umbraco.Content(1170);
    }
    <div id="footer">
    <div class="footer-col footer-col-238">
        <img width="115" src="@Umbraco.Media(footer.footerLogo).Url" style="padding-bottom: 15PX;" /><br />
        @footer.footerDescription       
    </div>
    <div class="footer-col footer-col-200">
        <h4>Contact MES</h4>
        @footer.footerContactAddress
    </div>
    <div class="footer-col footer-col-200">
        <h4>Send Us A Message</h4>
        @{   
            Html.RenderPartial("~/Views/Partials/mes-mini-contact.cshtml", new QuickContactModel());
        }
    </div>
    <div class="footer-col footer-col-238">
        <h4>Site Map</h4>
        @Html.Partial("mes-sitemap")
        <div class="clear-both"></div>
    </div>
    </div>
    
  • Yasir Butt 161 posts 371 karma points
    Apr 16, 2014 @ 21:47
    Yasir Butt
    101

    one error found in your code which is your controller name is QuickContactController in ajax form you are using like

     

    @using(Ajax.BeginForm("MESQuickContactPost","QuickContactController",
    controller name should be without controller
    @using(Ajax.BeginForm("MESQuickContactPost","QuickContact",
  • Phillip Turner 98 posts 412 karma points
    Apr 16, 2014 @ 21:50
    Phillip Turner
    0

    That totally fixed it!

    Kudos Yasir!

  • Yasir Butt 161 posts 371 karma points
    Apr 16, 2014 @ 21:52
    Yasir Butt
    1

    Thats Great :)

  • Phillip Turner 98 posts 412 karma points
    Apr 16, 2014 @ 22:01
    Phillip Turner
    0

    Hey Yasir. I can't mark the threat as answered so hopefully the OP will do it.

    Again, thanks mucho for the help.

  • Dan Sørensen 102 posts 327 karma points
    Apr 22, 2014 @ 10:31
    Dan Sørensen
    0

    Sure phillip :)

Please Sign in or register to post replies

Write your reply to:

Draft