Show a modal confirmation box in a JsonResult response from the controller based on a specific condition

Hello everyone, I am facing a unique situation: In my current view, there is a save button that serializes a form and sends it via Ajax to a JsonResult in the Controller. Within this JsonResult method, I am performing add/edit operations on tables in the database. My query revolves around whether it is feasible to display a confirmation box back in the view based on certain conditions. Below you will find snippets of my code. Thank you in advance for your assistance :)

Below is the snippet of javascript present in my view responsible for sending the form-data to the controller using ajax.

<script>
    function submitForm() {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("UpdateEvent", "EventCalendar")',
            data: $('#UpdateEventForm').serialize(),
            success: function (eventId) {
                $('#modal-edit-event').modal('hide');
                $('#calendar').fullCalendar('refetchEvents');

            }
        });
    }

This chunk of code represents my Controller logic handling the form-data retrieval:

 public JsonResult UpdateEvent(.........)
 {
   List<Guid> usersChanged = new List<Guid>();
   .
   .
   .
   if(usersChanged.Count() > 0)
   {
    //I would like to trigger a confirmation box at this point
   }
   .
   .
   .
   return Json(eventId, JsonRequestBehavior.AllowGet);
}

}

Answer №1

Achieving this is totally possible. You just need to provide the HTML markup required to display in the modal dialog.

In this scenario, I am utilizing the RenderRazorViewToString method (mentioned by Ben Lesh in their response on how to render a view as a string)

public string RenderRazorViewToString(string viewName, object model)
{
    ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                    viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                        ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

Now, you can simply invoke this method whenever necessary to obtain the string representation of your view result

public ActionResult UpdateEvent()
{

    if (SomeConditionHere)
    {
       var modalMarkup = RenderRazorViewToString("MyModalView", null);
       return Json(new { status = "failed", data = modalMarkup },
                                                            JsonRequestBehavior.AllowGet);
    }
    return Json(new { status = "success", eventId = 123 }, JsonRequestBehavior.AllowGet);
}

Supposing you have a view named MyModalView.cshtml containing the markup essential for the bootstrap modal dialog like so

<div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                   <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
    </div>
    <div class="modal-body">
        <h2>Modal content</h2>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
    </div>
</div>

Ensure that your ajax call's success event handler checks the returned json data and utilizes the data /eventId according to the value of the status property.

success: function (res) {
    $("#myModal").remove();
    if (res.status === "failed") {
        $('<div id="myModal" class="modal fade"><div class="modal-dialog" role="document">'
                +res.data 
                +'</div></div>')
            .modal();
    } else {
        alert("eventId is : "+ res.eventId);
    }

}

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

Is there a way to incorporate an 'ended' feature into the .animate() function?

I'm currently working on a jQuery statement where I want to activate pointer events once the button animation is finished. However, I'm unsure how to incorporate an ended or complete function. Any suggestions on how to approach this? $('#ce ...

Tips for accessing and saving content from a JSON file on your local machine into a variable

Hello all, I'm facing an issue with my script where I have a Json store in a variable. I want to save this json data in a local file to create a standalone and user-friendly website without too many components. Currently, my script looks like this: ...

Is there a way to implement seamless scrolling within an absolute element using Jquery?

Hey there! I recently implemented smooth scrolling on my website, but it seems to only work on single-page layouts. How can I make it function properly within an absolutely positioned scrollable element? Here are the link to my website and the correspond ...

Enhancing custom geometry with textures in Three.js

Trying to figure out how to apply a simple material with a texture map to a custom mesh? Look no further! Check out this demo I created to showcase what I'm attempting to do. /// MATERIAL var texture = new THREE.TextureLoader().load( "https://raw.git ...

Consistently scaling the Embla carousel slides for a seamless presentation experience

In my current project, I am utilizing Embla Carousels and aiming to incorporate a smooth slide scaling effect as users scroll through. The idea is for slides to enlarge the closer they get to the left edge of the carousel container, then decrease in size r ...

JavaScript: Reversing the Sequence of XML Elements

I am looking to reverse the order of this list using JavaScript. I have tried different methods that I know, but the below code shows it in a straight manner. I am not familiar with XML nodes and how to completely reverse it. <messages> <mess ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

Encountering an Error while uploading to a NodeJS FTP server

I am utilizing the library https://github.com/mscdex/node-ftp to transfer a file to an FTP server. Below is the code snippet that I am using: const Client = require('ftp'); console.log('CONNECTING...') const c = new Client ...

Updating JQuery function after window is resized

click here Currently, I am using slick-slider to showcase content in 3 columns by utilizing flexbox. The aim is to have the slider activated only on mobile view. This means that when the screen size shrinks down to mobile view, the 3 column flexbox transf ...

Is the setInterval function in JavaScript only active when the browser is not being used?

I am looking for a way to ensure proper logout when the browser is inactive using the setInterval() function. Currently, setInterval stops counting when the browser is active, but resumes counting when the browser is idle. Is there a way to make setInterv ...

Calculate the date and time three months before or after a specified date

I have the following start date : 2023-09-03T00:00:00+05:30 and end date : 2023-09-10T00:00:00+05:30 My objective is to deduct 90 days from the start date and add 90 days to the end date Afterwards, I need to convert it to UTC format In order to achieve ...

How to extract the value of a key from JSON using JavaScript

Need help with an API call to retrieve a list of subcategories? Here's an example of the JSON format: { "description": "Flower", "name": "Flower", "parent_id": "1" }, { "description": "Moon", "n ...

Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below: events: { load: () => { var chart : any = this; ...

HTML counterpart to PHP's include for JavaScript components

I am searching for a Javascript alternative to a method I have been using in PHP. Specifically, I want to streamline the basic setup of my pages: <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

The processing indicator fails to function properly when trying to refresh a jQuery datatable

I am currently customizing the loading indicator for the datatable using a spinner called startLoadGlobal(SPINNER_DATA_TABLE_FINANCEIRO_CARREGAR_REGISTROS) in jQuery. It works correctly when I initially load the datatable, however, when I reload it, the sp ...

Changing the 'null' string to null in JavaScript

Within an array of objects, some keys have a value of "null" as a string that I want to convert to null. Here is the code I tried: let obj = [{ "fundcode": "DE", "fundname": "Defens", ...

Retrieving a local variable within an AngularJS controller

Examining the code provided below: app.controller('Controller', function($scope, $http){ $scope.rep = []; $scope.tot = { name: '', marketValue: 0, cash: 0, legend: 'none' }; ...

RequestDispatcher.forward() does not work when servlet is invoked through an Ajax POST request

My login page involves user authentication through the firebase and sending the request to a servlet. When I click the submit button with correct credentials, the firebase authentication works, the servlet is called but an error is displayed in the browser ...

Guide on how to set a custom image as the cursor when clicking on an image through javascript

Does anyone know how to use javascript to change the cursor to a custom image by updating the cursor property of the entire page? I'm getting an error in the Chrome console that says: projetFinalPage1.html:626 Uncaught TypeError: Cannot read property ...

Troubleshooting the challenge of saving multiple records using ajax in Django

Having trouble saving my form multiple times? I want users to be able to fill out the form with as many dimensions as needed. For example, if they enter two dimensions, I want to save each one as a separate record in the database. Any guidance on how to ac ...