Incorporating post data into a Partial View

Main objective:

My goal is to enable users to click on a specific day on the calendar plugin and have a popup Bootstrap modal display events scheduled for that day.

Current Progress:

I am currently utilizing a javascript plugin called fullCalendar. Within this plugin, there is a dayClick event that I am implementing. Upon clicking a day, I have included AJAX code to send values via POST as shown below:

<div id="calendar"></div>
@Html.Partial("Modal",null)
    ...  
<script>
    $(document).ready(function () {
        $('#calendar').fullCalendar({
            height: 170,
            selectable: true,
            editable: true,
            defaultView: 'basicWeek',
            dayClick: function (date, jsEvent, view) {
                $.ajax(
                {                        
                    url: '@Url.Action("Index","Home")',
                    type: "POST",
                    data: JSON.stringify({ date: date }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    cache: false
                })
              $("#myModal").modal();                
            }
        });
    });
</script>

Following this, the process goes to the controller which then retrieves related data for that particular day and directs it to a partial view. Based on my debugging efforts, everything seems to be functioning correctly.

[HttpPost]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ActionResult Index(string date)
{
    if (date != null)
    {
       string[] dateSplit = date.Split(new char[] { 'T' });
       DateTime objDate = Convert.ToDateTime(dateSplit[0]);
       var content = db.Calendars.Where(x => x.startDate == objDate).ToList();
       return PartialView("~/Views/Home/Modal.cshtml", content);
    }
    else
       return PartialView("~/Views/Home/Modal.cshtml", null);
}

The Issue at Hand:

It appears that the data is not being passed correctly into the partial view, only displaying the initial null value. I originally thought that passing data through the post of the index would populate the partial view properly.

Could it possibly be that the javascript call $("#myModal").modal(); is being triggered before the data can fully populate? I've conducted some tests by including an if statement (Model != null) within all sections of code in the partial view, alongside an else statement that should display a paragraph with elements in it. However, it consistently shows the paragraph tag.

Here is the View Section:

@model IEnumerable<webby.Models.Calendar>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="padding:20.5% 15%;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">Events on @ViewBag.Date</h4>
            </div>
            <div class="modal-body">
                <table>
                @if(Model != null)
                { 
                    @foreach(var item in Model)
                    { 
                    <tr>
                        <td>
                            @Html.DisplayFor(model => item.events)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.DisplayFor(model => item.type)
                        </td>
                    </tr>
                    <tr>
                        <td>
                            @Html.DisplayFor(model => item.content)
                        </td>
                    </tr>
                    }
                  }
               </table>
             </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>
    </div>
</div>

Answer №1

To activate the modal window,

$("#myModal").modal(); 

You should execute this command within a .success function, rather than within the dayClick function. Additionally, make sure to pass it the data retrieved from your ajax call as well.

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

ReferenceError: 'exports' is undefined in the context of Typescript Jest

I'm currently delving into unit testing with jest and encountered an error that looks like this: > npm run unit > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771f181012374659475947">[email protected]</ ...

Avoiding the capturing of events on $( document ).mousemove

Each time the browser detects a $( document ).mousemove event, my function is invoked. The performance is smooth with an empty page, but once I introduce a div element and hover over it, the function gets executed twice: first on the document and then agai ...

invoking a boolean type JavaScript function

I'm currently working on calling a Page Method using AJAX. Take a look at the code below: <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" Text="Upload" onclick="btn_upload_Click" OnClientClick="return Validate();" /> ...

What is the best way to obtain the output produced by a function when a button is clicked

When I click on a button, the desired action is to trigger a function that adds a new property inside an object within a large array of multiple objects. This function then eventually returns a new array. How can I access and utilize this new array? I am ...

The worth of the scope is evident, yet it remains undefined when trying to access it

Currently, I am in the process of developing an AngularJS directive. However, I have encountered an issue where a scope variable appears to be undefined when attempting to access it. Interestingly, upon printing out the scope, it is evident that the variab ...

Learn how to extract data from the "this" object in JavaScript

Can anyone help me with retrieving the numbers generated by this code snippet? $("#100wattaren") .countdown("2018/01/01", function(event) { $(this).text( event.strftime('%D days %H hours %M minutes %S seconds') ); }); When I con ...

How to manually close the modal in Next.js using bootstrap 5

Incorporating Bootstrap 5.2 modals into my Next.js application has been smooth sailing so far. However, I've encountered an issue with closing the modal window after a successful backend request. To trigger the modal, I use the data-bs-toggle="modal" ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...

I am looking to retrieve data from the Graph API JSON and gradually refine my search to achieve successful

I am looking to retrieve data from the "fb_page_categories" endpoint, which provides an array of categories a page can be categorized under. The format for this request is as follows: GET graph.facebook.com /fb_page_categories? Once this request is mad ...

What is the best way to achieve the functionality of this ajax jquery using vanilla JavaScript?

I am attempting to replicate this jQuery ajax POST request in Vanilla JS, which currently looks like: $.ajax({ method: 'POST', url: window.location.href + 'email', data: { toEmail: to, fromName: from, ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

jquery is in motion while svg paths are at a standstill, waiting to

i have been attempting to incorporate a css-animated svg into my project. initially, the animation would start automatically, which was undesirable. after some research, i discovered that by declaring it as paused and then triggering it using jQuery with $ ...

Tips for choosing a specific point on a Vuetify <v-slider> using Cypress

Currently, I am exploring how my application responds when a user interacts with a specific area on a basic Vuetify <v-slider>. How can I replicate this scenario in a Cypress integration test effectively? For instance, to click on the center of the ...

Learn how to retrieve URL parameters using HTML code

I would like to update the URL without refreshing the page as I am using an AJAX function to refresh a specific div. The issue I am encountering is that when the div is reloaded via AJAX, it does not recognize the URL parameter. Below is my code (I have a ...

Learn how to send data from a MySQL server to a Node.js application using Socket.IO

I've been facing a challenge recently. I am attempting to listen for events from the @rodrigogs/my-sql events node package and then emit those events through socket-io to the react client. However, there seems to be a disconnect that I can't see ...

Navigating the website with curtain.js and anchor tags

Currently, I am working on a website located at www.TheOneCraft.co.uk. I have incorporated the curtain.js jQuery plugin to create animated slide/pages as users scroll down. However, I have been unsuccessful in making the navigation bar follow this animati ...

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

Error: The attempt to access the 'useContext' property of null has failed due to a TypeError

Nowhere in my React code am I using the useContext property. There is a compiled webpack file in an npm package with a component inside. When trying to use this component in my React app, it throws an error: Uncaught TypeError: Cannot read properties of nu ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...