What steps should I take to refresh my Partial View after a successful form submission?

Greetings, I hope this message finds you well. I have a help page on my website that includes an FAQ section (content served from a Web Service) and a button that displays a partial view. The partial view collects help request information and submits it to the Server using a standard form submission method.

My goal is to integrate AJAX functionality to display a success message without reloading the page once the information has been successfully saved.

I've attempted to return JSON data from the Controller and then use AJAX to update the page with the success message. However, this approach replaces the entire page contents with just the JSON data!

If you could provide some guidance or suggest a better approach on how to achieve this, I would greatly appreciate your assistance.

Below is a snippet of my Controller Action:

  [AllowAnonymous]
        public ActionResult Index()
        {
            FAQModel.Questions = Service.PopulateFAQQuestions();
            FAQModel.Answers = Service.PopulateFAQAnswers();

            return View("Index", FAQModel);
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<ActionResult> SendHelpRequest(RequestViewModel model)
        {
            model.RequestDate = DateTime.Now;
            await Service.SendHelpRequestAsync(model.Name, model.Details, model.RequestDate, model.Email, model.ContactNumber);

            return RedirectToAction("Index");
        }

And here's an excerpt from my Partial View:

@model MyProject.Models.RequestViewModel

<script>
    function Success() {
        var Success = document.getElementById("SuccessText");

       Success.innerHTML = "Request Submitted";
    }

    function Failure() {
        var Failure = document.getElementById("SuccessText");

        Failure.innerHTML = "Request Failed";
    }
</script>

@using (Ajax.BeginForm("SendHelpRequest", "Help", null, new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "Success",
        OnFailure = "Failure",
        UpdateTargetId = "SuccessText"
    }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="modal-content">
            <div class="modal-header" style="border-bottom: none !important;">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h3 class="modal-title">Support Request</h3>
            </div>

            <div class="container-fluid">
                <div class="form-group">
                    @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10" style="border-top: none !important;">
                        @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @id = "txtEmail", @placeholder = "E.G: Fred Flintstone" })
                        @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @placeholder = "E.G: example@example.com" })
                        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => m.Details, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(m => m.Details, new { @class = "form-control", @rows = "10", @style = "max-width:100%; max-height:100%; resize:none", @placeholder = "Please Enter Details (max 500 Characters)", @maxlength = "500" })
                        @Html.ValidationMessageFor(m => m.Details, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.ContactNumber, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.ContactNumber, new { @class = "form-control", @rows = "10", @placeholder = "E.G:00000000000", @maxlength = "15" })
                        @Html.ValidationMessageFor(m => m.ContactNumber, "", new { @class = "text-danger" })

                    </div>
                </div>

                <div class="col-md-12">
                    <div class="modal-footer">
                        <div align="left" class="col-md-6">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                        <div align="right" class="col-md-6">
                            <button type="submit" class="btn btn-default">Submit</button>
                        </div>
                    </div>
                </div>


            </div>
        </div>
    }

<div id =" SuccessText"></div>

Answer ā„–1

Implement the Insertmode "Replace" in your Ajax.BeginForm() function and then send back a partial view containing the success message.

By doing this, you can update the content of the "SuccessText" element as specified by the TargetId attribute. Don't forget to include the "jquery.unobtrusive-ajax.min.js" JavaScript library for this to function properly!

Answer ā„–2

I was able to troubleshoot and resolve the issue on my own! It turns out that my code was functioning correctly all along; however, I had forgotten to handle the results from my AJAX call.

@using (Ajax.BeginForm("SendHelpRequest", "Help", null, new AjaxOptions
    {
        HttpMethod = "POST",
        OnSuccess = "HandleSuccess",
        OnFailure = "HandleFailure",
        UpdateTargetId = "SuccessText",
        InsertionMode = InsertionMode.Replace

    }))

Here is the success function I implemented:

function HandleSuccess(result) {
      alert( result);
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a SingleOrArrayConverter for JSON property in F# (Adapted from C#): A Guide

I am currently in the process of transferring some well-established code from C# to F#, and encountering difficulties in getting it to function properly in F# The C# Code: ( Object I want to serialize ) public class Locality { public string category ...

Guide to incorporating Jquery-Comment into Angular versions 2 and beyond

I've incorporated the Jquery-Comment plugin into my Angular 2 project by adding the necessary script and css files to my Index.html page. However, when initializing the Comment TextBox id within a script tag, I encountered an error in the console. ...

Issues with retrieving information between AJAX and PHP (and vice versa)

I have a script that sends the value of a text input from an HTML form to emailform.php. This PHP file then adds the data to a .txt file. The issue I'm facing is setting the value of $email in the PHP file to match that of the HTML input field. Curren ...

Finding HTML source with regular expressions in Python: A guide

I've been wracking my brain trying to crack this problem. Although the numbers and names in this scenario are made up, the concept is the same. For instance, when I go to a link like 'https://graph.facebook.com/123' This is what I get bac ...

Chromium is having issues with updating the dynamic source attribute

One portion of my script that pertains to the question is as follows: <script type="text/javascript> function handleImageClick() { var image = $("#image_id"); $(image).attr("src", "ajax-loader.gif"); $.ajax({ ...

transferring information from browser storage to the server

On my web app, there is a feature that saves data to local storage and converts it to a JSON object. I'm interested in passing this local storage data to my server using AJAX, so that other clients of the web app can access it. Is there a way to accom ...

What is the best way to create a loop using JSON information?

Seeking assistance to create a loop using JSON data to display the title, link, and description of advertisements in HTML format. Provided is a JSON template with two ads, but my actual JSON contains 10-20 IDs. What am I overlooking in the code below? Sto ...

Please send the element that is specifically activated by the onClick function

This is the HTML code I am working with: <li class="custom-bottom-list"> <a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a> </li> Here is my JavaScript function for Upvot ...

Move the comment that is currently fixed to the top, following the old comments that have loaded above the

Iā€™m working on a comments section where there is a fixed comment displayed at the top by default.. <button>Show All Comments</button> <ul class="comments"> <!--Ajax loaded hidden posts--> <li class="fixed">Fixe ...

Refresh Content Using Ajax with jQuery Mobile's Link Click or Browser's Back Button

Alright, I've exhausted all options, time to seek advice from the professionals! I'm dealing with a multi-page JQM app. index.html - serves as the starting point and retrieves a list of projects via Ajax, everything is functioning perfectly - g ...

The jQuery .post method is not returning any data when using the done and fail functions

I've encountered an issue while attempting to execute a jQuery AJAX request and retrieve the data in the .done and .fail methods. Below is the snippet of code that triggers the AJAX request: async function doSomething(){ const addressValid = awai ...

Sending an image file using AJAX and jQuery

I am currently using Mustache JS to generate a template called 'addUser1' for display purposes. However, when I execute this code, only the image location is being sent to the server, not the actual image itself. What could be causing this issue? ...

Holding off on executing a function until a write stream finishes

I'm currently working on a project that involves fetching multiple JSON files from Google Drive and then converting them into objects within my code. My approach includes using a write stream to create the file locally and then parsing it with JSON.pa ...

Why won't the code for detecting the DEL key in a textarea work on my computer?

I've been trying to detect when a user presses the Delete key and came across this helpful tutorial here The code worked flawlessly on jsfiddle.net, you can check it out here- http://jsfiddle.net. However, when I copied the same code to my local comp ...

My script is unable to access the session variable

Two $_SESSION variables seem to be inaccessible in any script on my page, yet I can confirm their existence in the PHP code of the same page by using echo to display their values. When trying to display these $_SESSION variables in jQuery using the code b ...

Form_Open will automatically submit - Ajax Submission in CodeIgniter

I am facing an issue with submitting my form via Ajax. Despite setting up a function to prevent the page from refreshing upon submission, it seems like the form still refreshes the page every time I click submit. I even tried creating a test function to lo ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

How to prevent the back button from functioning in Android devices

It's so frustrating always hitting a dead end and I really need a clear answer. How can I disable the hardware back button on my app? And where should I input the code to disable it? I simply want users of my app to navigate within the app without usi ...

What issues can be found in this piece of JQuery script?

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> //waiting for the document to be ready $(document).ready(function() { ...

Combining Multiple Rows into a Single Record with Multiple Columns in PHP

Okay, so I have a bit of a tricky situation here that I need help with. Let me break it down for you. The challenge I'm facing is this: I have a MySQL table with around 600,000 rows and I need to export these records into a CSV file. The issue is tha ...