What is the process for running a script during partial view rendering?

My view is strongly typed to a CalculateModel where a user inputs information and then makes an ajax post to the controller. The controller performs calculations using this data and returns a PartialView strongly typed to the ResultCalculateModel.

The Result partial view contains a dynamically generated d3 chart with parameters from the ResultCalculateModel. Here is some code snippet:

 @model DTO.CalculateModel    
 //html helpers here for user input 

   <div id='divOutPutData'> </div>

 <script>
 function getResult() {

        $.post("/GetResult", $('#form01').serialize())
            .success(function (result) {
                $('#divInputData').attr('style', 'display:none');
                $('#divOutPutData').append(result);
        };

   function drawChart(s,p,c){
     //code
   };
    </script>

The controller action:

 public ActionResult GetResult(CalculateModel model)
 {
        ResultCalculateModel result = _calculateResult.Calculate(model);
        return PartialView("Result", result);
 }

The result Partial View:

  @model DTO.ResultCalculateModel //the parameters of the drawChart function are in this model.
  //some Razor Helpers which is working
   <div id="chartResult"> </div> //display the chart here

I am looking for a way to execute the drawChart function when rendering the partial view.

Answer №1

Maybe this can provide some assistance

//sample function for sending data, receiving result, updating HTML, and calling DrawChart function
function SendData() {
    $.post("/RetrieveResult", $('#formData').serialize()).success(function (result) {
        $('#inputSection').attr('style', 'display:none');
        $('#outputSection').append(result);
        //call function to interact with the newly injected data
        //retrieve values from the custom view (example IDs used)
        var x = $("#xId");
        var y = $("#yId");
        var z = $("#zId");
        DrawChart(x, y, z);       
    };
}

//example function
function DrawChart(x, y, z){
   //add your code here
};

Answer №2

Maybe you can include the necessary parameters directly in the .cshtml file itself within a hidden tag, like this:

<div id="drawChartValues" parameter1="value1" parameter2="value2" style="display: none;">
</div>

Then, in your JavaScript code, you can retrieve these parameters and use them:

function PostStuff() {
  $.post("/GetResult", $('#form01').serialize()).success(function (result) {
    $('#divInputData').attr('style', 'display:none');
    $('#divOutPutData').append(result);
    var p1 = $('#drawChartValues').attr('parameter1');
    var p2 = $('#drawChartValues').attr('parameter2');
    DrawChart(p1,p2);    
};

}

Answer №3

To effectively plot the graph using D3, instead of returning a partial view from your action method, return the necessary data in JSON format. Update your ajax call's success event to read and pass the data to the JavaScript method responsible for rendering the D3 graph.

 public ActionResult GetResult(CalculateModel model)
 {
        ResultCalculateModel result = _calculateResult.Calculate(model);
        return Json(result,JsonRequestBehaviour.AllowGet);
 }

Ensure the container div is retained in your main view.

<div id="chartResult"> </div>

In your JavaScript code:

<script>
 function getResult() {

        $.post("/GetResult", $('#form01').serialize())
            .success(function (result) {
                var s=result.SValue ;
                var p = result.PValu;
                var c =result.CValue;

                drawChart(s,p,c);
        };
   }
   function drawChart(s,p,c){
     //code to render the graph
   };
</script>

Make sure that SValue, PValue, and CValue correspond to the properties in your ResultCalculateModel.

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

Is it possible to link the _id of a mongodb array to its corresponding clientId in another array?

I am facing a challenge with 2 arrays retrieved from my MongoDB database. The first array is called users and it contains user objects structured like this: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1beb ...

What is the best way to transform an array that contains arrays into an array that contains objects with newly-defined properties?

Is there a way to transform this: [[a1, b1], [a2, b2]] into this format? [{x1: a1, y2: b1}, {x2: a2, y2: b2}]? Please note that the properties x1 and x2 are newly introduced with values a1, b1, etc. I attempted to achieve this with the following code sni ...

Using Vue's $emit method within a Promise

I am currently working on an image upload feature that is based on a Promise. Within the "then" callback, I am attempting to $emit an event named 'success'. Although my VueDevTools shows me that the success event has been triggered, the associate ...

SOLVED: NextJS restricts plugins from modifying HTML to avoid unnecessary re-rendering

My current scenario is as follows: I am in the process of developing a website using NextJS (SSR) I have a requirement to load a script that will locate a div element and insert some HTML content (scripts and iframes) within it. The issue at hand: It se ...

What is the reason for the initial DOM operation taking significantly longer than subsequent ones?

Why is the first operation much more despite the subsequent manipulation of the DOM being practically identical in time when both are written with the realization in JS and jQuery? Link to Javascript source // ES5 // Sending a message function sendMessa ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

The pagination feature is malfunctioning and is displaying all elements on every page instead of correctly displaying a

I am currently working with BootstrapVue 3 to create a component that uses a b-table. The issue I am facing is with the pagination functionality using b-pagination. My intention was to display only 2 objects per page, but instead of that, all objects are ...

Navigating within a React application - rendering JSX components based on URL parameters

As I work on developing a web-app with a chapter/lesson structure, I have been exploring ways to handle the organization of lessons without storing HTML or React code in my database. One idea I had was to save each lesson as a .jsx file within a folder str ...

Changing the value of a variable after iterating through an array in JavaScript

I'm just getting started with programming and teaching myself. I'm struggling to grasp how to update a variable by iterating through an array. Here's an array containing the best pies, each with its own price: [blueberry, strawberry, pumpk ...

Encountering a ValueError when attempting to validate form fields with Django and JavaScript

I encountered an error while trying to validate a field using Javascript and Django. Error: ValueError at /insert/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/insert/ Django Version: ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

What is the process for creating a folder using Firebase Cloud Functions with Storage?

How do I create a folder named "posts"? Storage bucket path --> gs://app.appspot.com/posts Code to generate thumbnail from storage object exports.generateThumbnail = functions.storage.object() .onChange(event => { const object = event.data ...

Tips for invoking a JavaScript class method from an HTML document

I've created a Typescript class that dynamically inserts an HTML element to a page after it's loaded. Here is the code snippet: const calcElement: string = ` <div class="container"> <span class="cc-title">Field</span> ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

Is there a way to incorporate pseudo-dynamic css into my projects?

I'm struggling with managing custom colored elements on my website. For instance, I have a hundred navigation squares on the site, each with its own unique color. The only solution I can think of is creating separate CSS classes for each color, but t ...

Implementing the map function in ReactJS to showcase data on the user interface

I seem to be facing an issue while attempting to utilize an array of data to display a <ul> element. Despite the console.log's working correctly in the code provided below, the list items fail to show up. <ul className="comments"&g ...

Is there a way to create an image gallery layout similar to Pinterest using CSS?

I am currently developing a dynamic PHP gallery that will feature thumbnails with the same width but varying heights. These thumbnails will be arranged from left to right, so I would prefer not to use a traditional five-column layout. I suspect that achiev ...

Tips for capturing a jQuery trigger in traditional JavaScript

I am trying to trigger an event using jQuery and I want to bind to it in a non-jQuery script. It appears that while I can bind to the event in jQuery using on, I am unable to do so with addEventListener. Check out this jsFiddle for a demonstration: http: ...

Retrieving data from a stored procedure with XSJS and storing it in a variable

I am currently facing a situation where I need to pass a session user as a parameter to a stored procedure in order to retrieve a receiver value. This receiver value needs to be stored in a variable so that I can use it in another function within an xsjs f ...

Display a component just once in React or React Native by utilizing local storage

I am struggling with a situation where I need to display a screen component only once using local storage. It's really frustrating. App.js ... constructor(props) { super(props); this.state = { isLoading: false, }; } component ...