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

Overlapping background images of flex elements in Safari

This webpage is designed as a single-page layout using Gatsby: <div className='mainContent'> <section className='contentSection'> <h1 className='header'>Heading</h1> <div c ...

Help Needed: Adding a Simple Element to jQuery Tabs Script

I recently came across a fantastic jQuery tabs script on a website called Tutorialzine. The link to the article can be found here. As I was implementing this script, I realized I needed to customize it by adding specific classes to certain tabs. Specifica ...

The customized uploading button functions seamlessly on desktop devices, yet encounters issues when used on

On my website, I have implemented a custom upload button alongside a hidden file input with the class .invisible-file-input. Here is how it is set up: Javascript $('.call-upload').click(function () { $(this).siblings('.invisible- ...

Show or hide a Div based on radio button selection problem

I've successfully implemented a Div visibility toggle using the code below: $('input[name="type"]').on('change', function() { var show = $(this).val(); $(".typechoice").hide(); $("#"+show).show(); }) <script src="h ...

Encountering a lack of response when making an ajax call to CouchDB

Being relatively new to CouchDB, I appreciate your patience. Currently, I have set up an instance of CouchDB on a VM. It can be accessed without any issues through the browser via futon or directly at: http://192.168.62.128:5984/articles/hot_dog Althoug ...

The functionality of the like button in Flask with jQuery/JSON seems to be malfunctioning

I am currently in the process of developing a small flask application and attempting to create a like button that can function without requiring a page refresh. After considering jQuery as a potential solution, I began writing some code. However, it appea ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

Monitoring Logfile in Ruby On Rails 3.1

Within my Ruby on Rails application, I have a set of scripts that need to be executed. In order to ensure they are working properly, the application must display and track the content of logfiles generated by these scripts. To provide more context: I util ...

Guide to Binding a JSON Property (Set or Array) to an Interactive Input Form in AngularJS

My input form is structured like this: <div> <div class="form-group"> <label for="inputQuestion" class="col-sm-2 control-label">Question</label> <div class="col-sm-10"> <input data-ng-model="publication.qu ...

Experiencing a '429 error: excessive requests' while utilizing Instagram API through a Python script

I am attempting to execute a script that logs into Instagram and uploads 10 images with randomly generated text on them. However, the following is the output I receive when trying to run the script: 2023-01-02 21:56:48,608 - INFO - Instabot version: 0.117. ...

What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: tr ...

Exploring Jasmine's Powerful Spying and Mocking Capabilities in JavaScript Prototypes

Hey everyone, I need some help with a JavaScript issue. So, I have a file named FileA.js which contains a prototype called FileAObject.prototype along with a function named funcAlpha(). Here's a snippet of what it looks like: File = FileA function s ...

Preventing variables from reinitializing in express.js

Within my app.js file, I invoke a search function that communicates with an LDAP server. Upon doing so, the server sends back a cookie which is essential for my subsequent queries. My intention was to save this cookie as an app.local variable in my app.j ...

Check if the input value was chosen by pressing Enter instead of clicking on it

There is an input tag with the following attributes: <input type="text" name="cOperator" class="form-control scale-input operator" placeholder="Enter your ID" autocomplete="off" onkeyup="ajax_showOptions(this,'getEmp',event)" required> ...

Using async and await inside a setTimeout function within a forEach loop

Currently, I am facing a challenge with scheduling background jobs in Node.js. I need each job to run only after the previous one has finished. Below is the code snippet inside a function: jobArray.forEach((item, i) => { setTimeout(async () => { ...

Passing data as a parameter to a page in React using history push

My Ionic React application includes functionality where the history.replace method is used to redirect users from the settings page to the login screen upon clicking a logout button. I am looking for a way to include a loggedOut flag in the redirection pro ...

Enabling automatic scaling during the rendering of an .stl file using three.js

I'm in the process of developing a server/webpage with the following functionality: Users can upload an .stl file to be 3D-printed The server executes a mesh repair script on the uploaded .stl file The corrected .stl file is displayed in the user&ap ...

Retrieve a div element using two specific data attributes, while excluding certain other data attributes

Here are some examples of divs: <div id="1" data-effect-in="swing" data-effect-out="bounce"></div> <div id="2" data-effect-in="swing"></div> <div id="3" data-effect-out="swing"></div> <div id="4" data-effect-out data ...

The console does not display the JSON data for requests and responses

I have successfully set up a server inside of VSCode, but unfortunately the request and response logs that I usually see in my terminal when running the server with npm start are not appearing. I would really like for them to display in the Debug Terminal ...

Transferring Information between a Pair of Controllers

Currently, I am utilizing angular version 1.x and faced with the challenge of sharing data between two controllers. In my mainctrl, I am working with the above model. The radiotmplt.radiohead=='IRU600v3' is utilized in firstctrl. Unfortunately, ...