What's the best way to display a bootstrap modal window popup without redirecting to a new page?

I am having trouble implementing a modal window that will display validation errors to the user when they submit a form. Currently, the window is opening as a new view instead of overlapping the existing form's view. How can I adjust my code so that the modal window pops up over the form?

Controller

[HttpPost]
public IActionResult Daily(Daily dailyReport)
{
    var dr = new ReportDaily();
    var rc = new ReportDailyCriteria();
    dr.Preview(rc, IntPtr.Zero, out Notification notification);
    if (notification.HasErrors) {
        var error = new Errors();
        string errorString = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine);
        error.ErrorList = errorString;
        return PartialView("_ErrorsModal", error);
    }
    return View(dailyReport);
}

Partial View

@model Test.Areas.Reports.Models.Errors
<!-- Modal -->
<div id="errorsModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title float-left">Error List</h4>
                <button type="button" class="close" data-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <label>Errors: @Model.ErrorList</label>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
            </div>
        </div>

    </div>
</div>

Answer №1

  1. It seems like you are currently submitting your form to a controller action using a full post back method. Instead, consider sending it as an ajax post, which will provide you with more flexibility when handling the response.
  2. I suggest rendering your modal on the initial page load and then exclusively working with JSON upon receiving results from the controller. This approach will simplify the parsing process of the response, removing any complexities involved in determining whether it is a partial view or something else that requires specific actions.

To integrate your partial view into the main view (remove Errors: @Model.ErrorList from the partial view and keep the label empty as it is no longer needed):

@Html.Partial("_ErrorsModal")

Your controller action returning Json:

    [HttpPost]  
    public IActionResult Daily(Daily dailyReport)  
    {  
        var dr = new ReportDaily();
        var rc = new ReportDailyCriteria();
        dr.Preview(rc, IntPtr.Zero, out Notification notification);
        if (notification.HasErrors) 
        {
            return Json(new
            {
                success = false,
                message = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)
            });
        }

        return Json(new { success = true });
    }

Update your ajax call for when you submit the form:

    $.ajax({
        type: 'POST',
        data: JSON.stringify($('#your_form_id').serializeArray().reduce(function(m,o){ m[o.name] = o.value; return m;}, {})),
        url: 'http://your_website/your_controller/Daily',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if(data.success){
                //actions to take when validation is successful...
            } else {
                $('#errorsModal .modal-body label').html(data.message);
                $('#errorsModal').modal('toggle');
            }
        }
    });

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

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

Each time a page loads, the react useContext feature is causing the web socket connection to reset

I have integrated websockets into various parts of my nextJS application and need to make sure they are accessible everywhere without resetting the socket connection. Whenever the connection is reset, it loses all the rooms it was connected to, causing iss ...

How can Javascript split main.js into two separate files using import or require?

Currently, my main.js file is functioning perfectly despite its length. However, I am interested in organizing my code by separating the functions related to 'y' into a separate file. In PHP, this process can be easily achieved with require(&apos ...

What is the best way to insert a Button within a Tab while ensuring that the indicator remains in the appropriate tab?

Is it possible to include a button inside a Tab? When I click on "Homepage", the tab switches correctly with the indicator showing on the right tab. However, when I click on "Profile", the indicator moves to the logout button instead. How can I fix this ...

Steps to Extract the key value from the parseJson() function

Could someone assist me in retrieving the value of the "id_user" key from the script provided below? JSON.parse({ "data": [ { "id_user": "351023", "name": "", "age": "29", "link": "http://domain. ...

`I'm experiencing difficulty sending JSON data to Typeahead using PHP`

I am having trouble passing an array of data from PHP to typeahead. I have tried various solutions but nothing seems to work. When I display the response on the console, it shows the array of strings but they are not populating in the typeahead field. PHP ...

What is the purpose of using double % in Java or JSP?

Yesterday, while reviewing some code, I came across a line that seemed very peculiar to me. In a JavaScript function, there is a condition checking for a string passed as a parameter in the following manner: "%%unsubscribe%%". See the snippet below for re ...

Dynamic Magento Profile Editing with AJAX

I am seeking assistance to update an avatar picture using Ajax in Magento. Currently, my form is functioning without AJAX, utilizing the default form action="<?php echo $this->getUrl('customer/account/editProfile') ?>" Here is my code : ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

Angular select tag failing to display input data accurately

When constructing select type questions for my web app using a JSON file, the code snippet for the select tag appears as follows: <div class="form-group" ng-class="{ 'has-error': form.$submitted && form[field.id].$invalid }" ng-if="fi ...

Trouble altering an attribute using jquery

Hey there, I'm struggling with changing the attribute for an id and can't quite pinpoint where I'm going wrong. It's not making things easier that I'm pretty new to this whole thing as well. I've created a function to ensure ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

The Rails application utilizes a background process application callback to initiate a specific event

I have a unique app that leverages the SuckerPunch gem and Carrierwave Backgrounder to efficiently upload and process images in the background of a cutting-edge rails application. As a user creates an instance of the Asset model, the image processing begin ...

What precautions can I take to safely and securely extend event handling?

I am currently developing a small JavaScript library that includes components requiring "messages" based on specific page events, which allow users to define response functions. I need to access general events like onkeydown and let users determine how eac ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...

Received an unforeseen outcome when processing POST data with Ajax

Every time I attempt to post data to the database using my ajax code, I end up with an unexpected outcome. Although I am able to submit the data, the displayed output is not correct. The issue seems to lie in my ajax code, as it is not executing properly. ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...

Optimal method for linking jQuery ajax requests to transfer data

Handling several asynchronous ajax calls in a specific order with information passing between them can be quite challenging. The current approach, even with just three API calls, can be cumbersome. Trying to manage five API calls makes it nearly impossible ...

Having trouble with flash messages in Node.js?

Could anyone shed some light on why the flash messages are not displaying properly in my situation? Here is how I'm attempting to utilize them: This snippet is from my app.js file: var express = require('express'); var app = express ...

Ruby on Rails: Making an Easy AJAX Call

i am encountering an issue with my ajax request: within my application, i am attempting to set up a basic ranking system. Once configured, whenever I click on the rank button, the page reloads and the rank is refreshed. I need help understanding how to i ...