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

Model-view-controller datasets incorporating viewbags

How can I utilize a dataset in a viewbag to showcase the data in a view? I have obtained a dataset from a model and stored it in a viewbag. My intention is to extract the datarows using a foreach loop within the view. Since I already have a variable bein ...

What steps can I take to give priority to a particular ajax call?

Every 10 seconds, two ajax based methods are executed. However, when I submit the form for processing, it waits for the previous ajax calls to complete before processing. I want to prioritize the form submission. Below is the script that I am using: func ...

Stop the Text Table from being highlighted

My webpage includes a dynamic table where users can select multiple rows. jQuery events and CSS are utilized to provide visual feedback when a row is selected. However, pressing the shift key sometimes causes text to become highlighted, which is not idea ...

Tips for transferring data from Controller to View using IEnumerable Model in MVC

Currently, I have a view containing 1700 records that need to be paginated using ajax for lighter page loading. The paging functionality works smoothly, bringing in a new set of records based on the selected page. Issue: The problem arises when displaying ...

Tips on sending form data, including a file, to Ajax using the onclick() method

My Modal Includes a Form: <div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content"> <div class="modal-dialog modal-lg" role="document"> ...

Modifying attributes of an object within a document using Mongoose

Encountering an issue where the sentiment object in my document is not updating. Within my Model Class, there's a field named sentiment of type Object structured like this: sentiment: { terrible: 0, bad: 0, okay: 0, good: 0, fantastic: 0 } ...

tips for transferring a javascript function value to a label within a webform

Currently, I am in search of the latitude and longitude coordinates for a specific address input by the user. Upon clicking a button, the script provided below is triggered to display an alert with the latitude and longitude values: <script type="text/ ...

Is there a way for me to update the button text and class to make it toggle-like

Is there a way to switch the button text and class when toggling? Currently, the default settings show a blue button with "Show" text, but upon click it should change to "Hide" with a white button background. <button class="btn exam-int-btn">Show< ...

Showing JSON information on a web browser

Here is a snippet of JSON data that I am working with: {"earthquakes":[{"datetime":"2011-03-11 04:46:23","depth":24.39999999999999857891452847979962825775146484375,"lng":142.36899999999999977262632455676794 ...

Creating an HTML Canvas effect where images are placed onto another image

Looking to create a similar effect as seen on this website () On this site, users can upload their images (4000 * 400) and have the option to add Mickey Mouse ears over their image before saving it. The Mickey Mouse ear is resizable from all four sides f ...

Dynamic content loading for Twitter Bootstrap Popover using Ajax

Below is my code for dynamic content loading in a popover using AJAX. The popover displays correctly after the initial load, but there is an issue with its behavior on the first "show" event – it appears and disappears immediately. $("a.mypopover"). ...

Is there a way to execute code right before the jQuery submit() function is run?

I'm currently facing an issue with executing codes before a validation function runs in my form. I have tried different methods including referring to How to order events bound with jQuery, but without success. This is the code snippet I am working w ...

Error message: "npm start cannot locate package.json file, even though the file is present

As I attempt to execute npm start within my Node.js project directory, I am facing a challenge. Despite having the package.json file in the correct location (C:\Myfirstproject\Vinci\Projet_Web), I keep encountering an error message that read ...

Mongoose: Enhancing Arrays with maximum values for each item

How to Update an Array Property in Mongoose with Item-Wise Max and Default Null Upon Instantiation I have a MongoDB collection that stores time series data in a fixed-length array (1 item per minute, 1 document per day). { 'series': '#1& ...

Accessing the IP Address with SQLDataReader

Currently, I am working with an ASP.Net application and facing a challenge. I need to extract IPv4 information from a SQL database using SQLDataReader. The issue I'm encountering is that when reading an IP from SQL, the data type is binary, and I&apos ...

Prevent mobile users from entering text with Material UI Autocomplete on keyboard

Currently, I am utilizing the Material UI Autocomplete component for multi-select functionality. Although it functions perfectly on desktop, I want to prevent keyboard input on mobile devices and only allow touch selection. Essentially, I do not want the v ...

Decoding JSON in C# with no specified properties

I'm working on my desktop application and I need to convert a JSON file into a list of key-value pairs. Each key should be unique and the corresponding value should contain another list of key-value pairs. Here is an example structure of the JSON stri ...

Hiding a parent DIV in JS based on specific content: Here's how

I need help figuring out how to hide multiple parent DIVs based on the content of a specific child DIV. Here's an example: <div class="report-per-day"> <div class="report-day">26 May 2022</div> <div class=" ...

Tips for retrieving the text value on keyboard enter press without triggering form submission

I am currently working on a feature where hitting the Enter key in a textbox should not automatically submit the form. The textbox is located within a form: @Html.TextBoxFor(model => model.ID, new { @class = "form-control input-sm", placehold ...

Submitting a form using Ajax without needing to navigate away from the current page

I'm facing an issue with submitting the Ajax form to prevent the page from redirecting to another page. The script I've implemented is still directing to trolley1.php instead of staying on the current product page. The objective is to send the da ...