Implementing the use of a partial view in ASP.NET MVC with the help of JavaScript

I am faced with a challenge of displaying 15 different partial views based on the user's selection from a menu tab. Essentially, I have these 15 menu tabs on one side of the page, and when a user clicks on a tab, the content related to that tab should be shown.

In addition, Knockout is being utilized in this scenario.

Upon page load, I populate 15 Knockout observables (

self.tab_A(), self.tab_B(), ...self.tab_N()
) with data.

The code structure looks something like this: Here is the view.

<ul id="tabs">
    <li>
        <a data-bind="click: function(){ $root.ShowHideDiv(tab_A.id); }" style="cursor: pointer;">
           Tab A
        </a>
    </li>

    <li>
        <a data-bind="click: function(){ $root.ShowHideDiv(tab_B.id); }" style="cursor: pointer;">
         Tab B
        </a>
    </li>
    ...
    ...
</ul>   

The partial views are pre-loaded but hidden from user view.

<ul>
    <li id="tab_A" style="display: none" class="hiddenDivs">
        @{Html.RenderPartial("~/Views/Claims/FroiReport/_Insurer.cshtml");}
    </li>

    <li id="tab_B" style="display: none" class="hiddenDivs">
        @{Html.RenderPartial("~/Views/Claims/FroiReport/_Insurer.cshtml");}
    </li>
</ul>

Displaying div using script on click event.

 self.ShowHideDiv = function (tabToShow) {
        console.log(tabToShow);
        $('.hiddenDivs').html('');
        $('#' + tabToShow).show();
    };  

Everything works well for 3-4 views, however the design breaks for the remaining views, possibly due to too many hidden divs.

Considering this issue, I attempted loading specific views at runtime rather than pre-loading them all. When a user selects a tab, the corresponding partial view is fetched and displayed.

My attempt:

self.ShowHideDiv = function (tabToShow) {
    $('.hiddenDivs').html('');
    var view = getValueFromDict(dict, tabToShow); 
    $('.hiddenDivs').load('/Claims/ReturnPartialView/?partialViewName=' + view);
};

This approach failed as there was no associated Action/Controller for the views, hence loading the view directly using javascript/jquery was not possible.

Another alternative I explored was creating a controller to return a partial view.

public ActionResult ReturnPartialView(string partialViewName)
        {
            return PartialView(partialViewName);
        }

And calling it like this:

self.ShowHideDiv = function (tabToShow) {
    $('.hiddenDivs').html('');
    var view = getValueFromDict(dict, tabToShow);
    $('.hiddenDivs').load('/MyController/ReturnPartialView/?partialViewName=' + view);
}

Although this method successfully loads the desired view, the KnockOut observable linked with that view appears as null.

I have heard about KO templates which could potentially solve this problem, yet I haven't explored them fully (but I plan to do so next). If anyone has an alternative solution without utilizing KO templates, I would appreciate the insights.

Thank you for your patience in understanding my situation.

Answer №1

If you want to achieve this using jQuery, it can be done in two simple steps. First, from your view, trigger the desired controller action either after the DOM has loaded or when a specific event occurs. In this example, I am calling the controller after the DOM is ready. You have the flexibility to use either the GET or POST method for hitting the action endpoint.
In the $.ajax function, I have included the option async: false to ensure that the current statement completes before moving on to the next one within the function.

<script>
    $(document).ready(function () { 
        $.ajax({
            url: '/Controller/ActionName',
            type: 'POST',
            async: false,
            data: { ModelField: value},
            success: function (result) {
                $("#your_desired_div_id").html(result);
            }
        });
    });
</script>

The specified action will return a view model as a result to the ajax.post function. Once the post request is successful, the content of your_desired_div_id will be updated with the contents of the partial view.

 [HttpPost]
public ActionResult ActionName  (ModelName ModelField)
{
    var dBList= (from myTable in db.tableModel where myTable .column == ModelField.column  select  myTable).ToList();
         return PartialView("_PartialView", dBList) 

}

Answer №2

Explained in further detail here..

Answer №3

To properly integrate a partial view into your project, creating a controller action specifically for returning the partial view is essential.

public ActionResult RenderMyPartialView()
    {
        return PartialView("_MyPartialView", new MyPartialViewModel());
    }

This controller action can then be accessed from JavaScript as needed. Just ensure that the partial view is located in the appropriate Views folder under a subfolder matching the controller's name.

I trust this explanation proves useful to you!

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

Instructions for properly formatting a date extracted from ASPX JSON through AJAX

Recently, I have been extracting data from a MySQL database, converting it into JSON format, and using AJAX to display the data on a Chart.JS. However, there is an issue with the date values being formatted as: /Date(154564434687)/ Below is the JQuer ...

React Checkbox malfunctioning: Troubleshooting and solutions

I have thoroughly researched for a solution to my issue before resorting to posting this question. Unfortunately, none of the answers I found seemed to resolve my problem. Despite trying various methods such as changing, clicking, and checking, my checkbo ...

Converting JavaScript code into PHP syntax

I'm curious about code organization. The original code in this snippet is functioning properly: <?php if (isset($_POST['submit'])){ ... ... $invalidField = 2; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD ...

Forced page redirection in PHP

I am facing an issue with my page that is being called through JQuery ajax. I am making updates in the page experience.php, and the update function is working smoothly. <?php if( isset($_POST["update"]) ) { $status = false; $status = $ ...

I'm having trouble getting the function inside onLoad to run in my Next.js project - can anyone help

While I was exploring nextjs.org and following the tutorial, I encountered an issue where the function inside onLoad wasn't executing. It's puzzling because there was no call made to that link in the networks tab of my browser's developer to ...

Error encountered in React Native packager due to naming conflict between "lodash" and "yeoman-generator" libraries

Issue Description Within my current project, I am utilizing "react-native": "0.36.0" along with the following dependencies: "lodash": "^4.15.0" "yeoman-generator": "^0.24.1" Upon using versions above "^3.10.1" for "lodash" and "0.21.2" for "yeoman-gene ...

Button to close Jquery Dialog

I've set up a custom alert UI using jQuery UI, but I'm having trouble getting the close button to work properly. Here's my code snippet where I'm trying to override the default alert() function with jQuery UI dialog as described in this ...

Combining strings using the PHP preg_replace function

I'm looking for assistance with using Ajax to send JS variables to my PHP script in order to modify the background color. Can you provide guidance on how to achieve this? I am struggling with how to concatenate strings and utilize the $mavariable vari ...

What is the significance of the "rc" within the version structure of an npm package?

Can someone help me understand what the rc in 2.2.0-rc.0 signifies? I'm curious if it indicates that this version is ready for production use. ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

Auto-collapse sidebar upon clicking anywhere on the page

I have a dynamic sidebar that appears when the user clicks on a hamburger button. Here is the layout: $('#nav-toggle').click(function() { if($('#nav-toggle').hasClass('active')){ $('.menu').animate({ r ...

Executing follow-up tasks using multiple partial views in MVC3 on ASP.NET

Although this question may have been asked before, I am seeking guidance on how to approach implementing a specific scenario. In my ASP.NET MVC3 controller, I need to create a view that includes multiple partial views, each interacting with the database fo ...

Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers. Data Collection 1 (Controller Name): [{id:1,"name":"jakov"},...] Data Collection 2 (Controller Nickname): [{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...] I send data from C ...

Setting up SKPM (Sketch Plugin Manager) using npm

I've been trying to install a specific npm package, but I keep encountering numerous errors that are unfamiliar to me. It's important to note that these errors occur after running the command sudo npm install -g skpm: gyp ERR! configure error g ...

Ways to verify if a string contains a specific template literal in javascript

I attempted to verify this by using the str.includes('${') method as a straightforward approach, but it did not produce the expected results. I found that it also returned strings that didn't contain the specified characters. For instance, ...

Is it possible to dispatch actions from getters in Vuex?

Fiddle : here Currently, I am in the process of developing a web application using Vue 2 with Vuex. Within my store, I aim to retrieve state data from a getter. My intention is for the getter to trigger a dispatch and fetch the data if it discovers that t ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...

Adding an additional stroke to a Material-UI Circular Progress component involves customizing the styling properties

I am attempting to create a circular progress bar with a determinate value using Material-UI, similar to the example shown in this circular progress image. However, the following code does not display the additional circle as the background: <CircularP ...

Create a new build for testing and debugging using create-react-app

Currently, I am in the process of developing a web application that utilizes a React frontend and is powered by a golang api layer. Although I do not have extensive experience with Javascript, I find myself struggling with the Node build system. I am loo ...

Failure to display React component on screen

I have developed a React microfrontend application consisting of two sub-apps rendered through the container/ project. Both sub-apps render perfectly in isolation on localhost:8083. However, when attempting to view them via localhost:8080/dashboard, I am p ...