Determine if a JavaScript code in my ASP view will be executed based on control from the controller

Working on an ASP.NET MVC4 system, I have a javascript code that displays a performance graph of students when the page loads.

Here is the code for the graph:

<script>
    window.onload = function () {
        var r = Raphael("holder"),
            txtattr = { font: "20px sans-serif" };

        var lines = r.linechart(30, 30, 600, 440,<%= Json.Encode(ViewBag.dates) %>,<%= Json.Encode(ViewBag.Grades)%>, {axisxstep : 6,nostroke: false, axis: "0 0 1 1", symbol: "circle", smooth: false }).hoverColumn(function () {
            this.tags = r.set();
            for (var i = 0, ii = this.y.length; i < ii; i++) {
                this.tags.push(r.tag(this.x, this.y[i], Number(this.values[i]).toFixed(5), 160, 10).insertBefore(this).attr([{ fill: "#fff" }, { fill: this.symbols[i].attr("fill") }]));
            }
        });
</script>

The data for the graph is retrieved from the function DisplayGraph in the controller. See the controller code below:

public ActionResult DisplayGraph(String InputStudent = "IP11")
{
    // Controller logic to fetch data for the graph
}

When a new student joins the school, I want to display a message instead of the graph. How can I control the execution of javascript from the controller?

Any help would be greatly appreciated. Thank you

Answer №1

Is there a way for my controller to determine when to execute a javascript function and when not to?

One way to do this is through a view model. The view model should contain all the necessary information for rendering the view, including any scripts or links to scripts.

It is recommended to minimize the use of ViewBag and instead use strongly-typed models.

Model

public class MyViewModel {
    public bool DisplayGraph { get; set; }

    public List<object> Data { get; set; }

    public List<int?> Dates { get; set; }

    public List<double> Grades { get; set; }
}

Controller

public ActionResult Index(){

    var model = new MyViewModel();
    model.DisplayGraph = !IsStudentNew();

    // set other properties of the model here, avoiding the use of ViewBag

    return View( model );
}

View

@model MyViewModel

@if( Model.DisplayGraph ){
    <script>
        // javascript for displaying the graph should be placed here
    </script>
}else{
    <div>No statistics available.</div>
}

Answer №2

One way to enhance your model is to include a property called GraphText. This property can be displayed on top of the graph. If there are statistics available, you can leave this property empty. However, if there are no statistics, you can assign it a default value:

public class YourModel {
    public IList<Statistic> StudentStatistics { get; set; }
    public string GraphText {
        get {
            return StudentStatistics.Any() ? "" : "No statistics available yet";
        }
    }
}

After updating your model, you can then simply render the GraphText property on top of the graph in your view.

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

Having trouble pre-populating the input fields in my form. Any assistance would be greatly appreciated. Thank you!

I am currently diving into the world of MERN stack development and working on a basic app that involves adding, updating, and deleting items from a menu. Specifically, for the update feature, I am trying to prepopulate the input fields with existing item d ...

Removing item from Angular service

Within my Angular 2 application, I have created a service called events.service.ts: const EVENTS = { 1512205360: { event: 'foo' }, 1511208360: { event: 'bar' } } @Injectable() export class EventsService { getEvents() ...

Encountering a React clash while integrating Material UI

Upon trying to utilize the AppBar feature in Material UI version 0.16.6, I encountered the following error: Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created within a c ...

Tips for choosing a href link from a JSON data structure

I'm struggling with JSON. I have a JSON object that looks like this: {main: "<a href="www.google.com"><img src="google_logo.png"></a>"} This is just a small part of my code. For example, I access the "main" object with json.main an ...

Displaying individual attributes of objects through v-for loop

I have created a table-making component to streamline the process of creating multiple tables. Each table consists of three key elements: The object (an array of objects with one row per object) Headers specific to each table The object properties that n ...

Using a jQuery script, you can enable a back button functionality that allows users

I created a survey to assist individuals in determining where to go based on the type of ticket they have. However, I am currently facing difficulties with implementing a "Back" button that will display the previous screen or "ul" that the user saw. Initia ...

Ways to display a jQuery alert when navigating on a webpage

I am looking to enhance my page navigation by implementing a jQuery confirmation message with 'Yes' and 'No' buttons. This way, when I navigate from one page to another, I can decide whether to proceed or stay on the current page. Inst ...

How about using a JQuery variable?

I'm a beginner in jQuery and I have this code snippet that displays a div when a specific link on a map is hovered over: <div id="locationmap"> <a class="linkhide" id="link1" href="#">Occupier 1</a> <a class="linkhide" id ...

Node.js Multer encountering undefined req.file issue when handling multiple file uploads

FIXED: ( NO req.file ) ( YES req.files ) My project requires the ability to upload multiple files. If single image uploads are working but multiple image uploads aren't (uploading to files), I need req.file.filename in order to write the image path ...

Methods for validating ajax response with Jasmine

I'm a newbie when it comes to jasmine and I'm trying to figure out how to verify if a specific node is present in the ajax response. Currently, I'm using grunt to run jasmine from the command line and have successfully tested if a function i ...

Creating a dropdown navigation menu using jQuery

I have been experimenting with creating a customized Drop Down menu using ul li and Jquery, following this helpful Tutorial. Here is the sample HTML Code for testing: <div id="dd" class="wrapper-dropdown-3" tabindex="1"> <span>OS</span> ...

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

Discovering an element within an HTML response using jQuery AJAX

Check out the code snippet below: ajax_obj = $.ajax( { data: data, success: function(answer) { console.log(answer); console.log($('#table_conferences_tbody', answer).html()); ...

When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is. Here is my class: export default { name: "Contact", component ...

Algorithm to identify the highest sum of two numbers in a disorganized array of whole numbers

I am looking to create a function that can identify the largest pair sum in an unordered sequence of numbers. largestPairSum([10, 14, 2, 23, 19]) --> 42 (sum of 23 and 19) largestPairSum([99, 2, 2, 23, 19]) --> 122 (sum of 99 and 23) largestPairSum ...

Ar.js results in objects experiencing deformation or modification when manipulated

Recently, I started experimenting with Ar.js and encountered an issue where the objects displayed on the screen seemed distorted. To illustrate this problem, let me share a basic A-Frame example featuring a perfectly round sphere: <!DOCTYPE> <html ...

Ways to adjust the visibility of a div element multiple times using javascript and css

I implemented a popup feature in my application: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()" ...

The format for a DateTime field in a JSON string array is as follows: yyyy-MM-dd hh:mm:ss

I am working with a JSON array string pulled from a database and I need to format the DateAndTime field into yyyy-MM-dd hh:mm:ss. This formatting needs to be flexible as the data passed through will vary, except for the DateAndTime. Here is my current att ...

A comparison of Vue's import paths: exploring the variations

Exploring the world of Vue has been exciting but I'm a bit puzzled by the syntax used for importing different libraries. Take, for instance, this import statement: import Vue from 'vue'; import axios from 'axios'; Where do these r ...

Converting a Jquery object into a Javascript object

Can someone help me decipher this piece of code? //... obj.dd.on('click', function(event){ $(this).toggleClass('active'); return false; }); //... $(function() { var dd = new DropDown( $('#dd') ); $(doc ...