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

How come my JavaScript regular expression doesn't function properly when applied to elements in an array?

let numbers = new Array('1','2','3'); let letters = new Array('a','b','c'); let length = numbers.length; let str = 'abcdefgabcdefg'; for (let i=0; i<length; i++) { let regex = new ...

Displaying a Laravel variable in an Ajax callback to trigger a separate Ajax function

What I am attempting to accomplish here is quite complex. I aim to utilize one Ajax function across my website to manage information updates. Essentially, a universal update script that will trigger upon form submission. The challenge I am facing is that ...

What could be the reason for the full name not being updated in the model when the last name is changed

Can you explain why the full name in the model does not update when I change the last name? You can view the code on Plunker: http://plnkr.co/edit/cqmwJc5dpoDWvai4xeNX?p=preview var loginCntrl=function($scope){ $scope.testClick =function(){ $scope. ...

Populate dropdown list dynamically in Codeigniter using AJAX and jQuery

Although this question may appear to be a duplicate, none of the other answers provided have solved my issue. My query pertains to populating a dropdown using ajax/jquery. While I can successfully send and receive data in JSON format, it doesn't seem ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

Execute and generate a continuous loop in JavaScript

I successfully implemented an image slider using pure PHP, but encountered issues when integrating it into Yii framework. The images were not loading due to the following reasons: - JavaScript block was not loading image numbers. - I am unsure how to load ...

Require Google Chrome to show a blank page upon refresh

After reloading the page in either IE/Edge or Chrome/Firefox, I noticed a significant difference. IE/Edge clears the page and displays a white page, while Chrome/Firefox does not. I'm wondering if there is a way to use JavaScript to instruct Chrome/F ...

Hiding elements in FireBase and Angular based on user identification

Currently venturing into the world of Firebase in conjunction with AngularJS after previously working with php and server-side rendered pages. I am grappling with how to securely hide specific parts of an application from certain users. I have three disti ...

Is it possible to forecast an on click event using jQuery?

I have encountered a specific issue. Within my code, there are certain elements, specifically <li> elements, that undergo a particular operation triggered by a click event: $('.panelTabs li').on('click', function () { // ..som ...

"Uh-oh, looks like there's an

When I click the button, a warning pops up and the form gets duplicated. Is there an error in the code? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ...

Including extra js files disrupts the jQuery IntelliSense functionality

After enjoying the benefits of jQuery IntelliSense in VS2008, I decided to add a reference to jQuery UI. However, upon doing so, I noticed that the jQuery IntelliSense disappeared. It seems that referencing another .js file in the document causes this is ...

Unpacking Reddit's JSON data in a Node environment proves challenging as the Javascript parser seems to have a distaste for

Hey there, I hope everything is going well! I've been working on a project that involves scanning the JSON data from reddit.com/r/pics. My goal is to extract a random image and display it on a webpage. The issue I'm facing is that Reddit's ...

JavaScript code for validating two passwords is malfunctioning

I'm currently working on a registration form for my website and I'm trying to implement a JS script that compares two password inputs (password and repeat password) and displays a message saying "passwords are not the same." Below is the code I h ...

Peer-to-peer Ajax image sharing

Currently, I'm utilizing Ajax to fetch images from a remote server. Initially, I attempted this by directly using the URL of the remote server - resulting in the returned image being a string (given that's how Ajax communicates). To rectify this, ...

retrieve the month and year data from the input date

I encountered a situation where I'm working with the following unique HTML code: <input type="date" id="myDate"/> <button type="button" class="btn btn-secondary" id="clickMe">MyButton</ ...

Display a text box upon clicking an item

I've been curious about how to create the effect of a text box or div that appears when clicked on, similar to what you see in this. Scroll down and click on "show patchnotes"; I've been puzzled by this for a while but haven't come across a ...

Weapons of Mass Destruction - receive markdown content

My application is utilizing a markdown editor from Google Code. $(document).ready(function () { var converter = Markdown.getSanitizingConverter(); var editor = new Markdown.Editor(converter); editor.run(); }); <div class="wmd-panel"> ...

Techniques for determining if a file is empty using jQuery

Just starting out with JS. I want to validate the file input element before form submission using jQuery/JavaScript. I've researched various solutions, but nothing seems to be working for me. I'm trying to avoid displaying "/c/fakepath" as the ...

Error message "Undefined is not a function" occurred while using jQuery's .replace and scrollTop functions

I'm having issues with the scroll function in my code. It doesn't seem to be able to locate the ids in my HTML, even though I can't figure out why. I had a previous version that worked perfectly fine (unfortunately, I didn't save it D:) ...

Before the file upload process is finished, the progress of tracking Angular files reaches 100%

I am currently developing a service that is responsible for uploading a list of files to a backend server. createFiles(formData: any, userToken: string): Observable<any> { const headers = new HttpHeaders({'Authorization': 'Bearer ...