Avoid creating empty blocks in ASP.NET MVC

I'm working on some back-end code

Take a look at the code snippet below

[HttpGet]
    public ActionResult GetQuestions()
    {
        var _id = TempData["ID"];

        var questBlock = db.QuestionBlocks
            .Where(x => x.Interview_Id == (int?) _id)
            .Select(x => new
            {
                ID = x.Block_ID,
                Question1 = x.Question1,
                Question2 = x.Question2,
                Question3 = x.Question3,
                Question4 = x.Question4,
                Question5 = x.Question5,
                Question6 = x.Question6,
                Question7 = x.Question7,
                Question8 = x.Question8,
                Question9 = x.Question9,
                Question10 = x.Question10,

            })
            .ToList();
        return Json(questBlock, JsonRequestBehavior.AllowGet);

    }

Some questions may not have values.

On the front-end side, I display these questions in the View

<script>
$(document).ready(function() {
    loadQuestionBlock();
});
function loadQuestionBlock() {
    $.ajax({
        url: '@Url.Action("GetQuestions", "Interview")',
        contentType: 'application/json; charset=utf-8',
        type: 'GET',
        dataType: 'json',
        processData: false,
        success: function(result) {
            var email = result;
            for (var i = 0; i <= email.length - 1; i++) {
                var question =
                    '<div class="activeQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
                        email[i].Question1 +
                        '</div>' +
                        // additional questions ...
                $("#questions").append(question);
                $('.hiddenQue').each(function() {
                    if ($(this).text().trim() === '') {
                        $(this).hide();
                    }
                });

Above, I used

$('.hiddenQue').each(function() {if ($(this).text().trim() === '') {$(this).hide();}});
to achieve this functionality. Is there a better way to accomplish it?

Answer №1

Incorporate an if condition within the for loop to verify whether there is a question present or not. This approach should prove effective for your requirements.

 <script>
       checkQuestions();

       function checkQuestions() {
           $.ajax({
               url: '@Url.Action("QuestionBlocks", "Home")',
               contentType: 'application/json; charset=utf-8',
               type: 'GET',
               dataType: 'json',
               processData: false,
               success: function (result) {
                   var data = result;
                   for (var i = 0; i <= data.length - 1; i++) {
                       var questionBlock = "";
                       for (var j = 1; j <= 10; j++) {
                           var currentQuestion = data[i]["Question" + j];
                           if (currentQuestion) {
                               questionBlock += '<div class="activeQuestion" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +
                                                currentQuestion +
                                        '</div>';
                           }
                       }
                       if (questionBlock != "") {
                           $("#questions").append(questionBlock);
                       }
                   }
               }
           });
       }
    </script>

Answer №2

Give this a shot!


    <script>
    $(document).ready(function() {
    fetch_questions();
    });
    function fetch_questions() {
     $.ajax({
     url: '@Url.Action("QuestionBlocks", "Interwier")',
     contentType: 'application/json; charset=utf-8',
     type: 'GET',
     dataType: 'json',
     processData: false,
     success: function(result) {
        var email = result;

        for (var i = 0; i <= email.length - 1; i++) {
     var question='';
     var Question1='';
     var Question2='';
     var Question3='';
     var Question4='';
     var Question5='';
     var Question6='';
     var Question7='';
     var Question8='';
     var Question9='';

     email[i].Question1==''?Question1='':Question1='<div class="activeQue" 
                   style="font-size:20px;position: absolute;top: 50%;left:  
          50%;transform:     translate(-50%, -50%);">' +email[i].Question1 +
                    '</div>'
       question=question+Question1
       //Repeat this process for all questions

            $("#questions").append(question);
            //$('.hiddenQue:empty').hide();     

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

Error occurred while making a request in React using Axios: TypeError - Unable to retrieve the 'token' property as it is undefined

After successfully receiving a token from logging in with React Redux, I attempted to authorize it using the token. However, an error occurred stating Axios request failed: TypeError: Cannot read property 'token' of undefined. The token is stored ...

Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error: TypeError: Cannot set property ' ...

The transformation of a Blender model in THREE.js results in a completely new and distinct

I have a Blender model that I'm trying to integrate into my website using THREE.js, but I'm encountering issues with the GLTF file rendering. The model appears broken with missing elements, misplaced objects, and incorrect lighting. I've tes ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Tips for Removing the Default UI Razor Pages in ASP.NET Core 2.1 Identity

Looking to make changes to the ASP.NET Core Identity UI routing? Check out this question: Change routing in ASP.NET Core Identity UI? Javier suggests a few options for customizing the URLs: Utilize the scaffolding element of the Default UI and c ...

Attempting to deploy a GitHub repository onto Railway.app has led to an Application Error. It seems like the issue may lie in whether your app is

I encountered an Application Error while deploying my project to railway.app. The error message prompts, "Is your app correctly listening on $PORT?". Initially, my project was a combination of JS and jQuery. However, I later integrated webpack.config.js t ...

Creating a dynamic list structure using <ul> and <li> tags in a CSHTML ASP file

I am aiming to design a visually appealing structure using ul li for categories. Each line of the structure should consist of three elements: <li> <ul class='kwicks kwicks-horizontal'> <li></li><li></l ...

Obtain an identifier to be used as dynamic data in an ajax request with jQuery

I am struggling to extract the id from links that trigger the same ajax function. I have over 30 links generated dynamically, as shown below: <a href="javascript:void(0)" id="105">Item 105</a> <a href="javascript:void(0)" id="379">Item 3 ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

Issue with BackboneJS TypeError

I attempted to use the example below, but I encountered an error stating "TypeError: _.has is not a function". Example: I have experimented with different versions of jQuery and Backbone (uncompressed), yet the same error persists. Can anyone offer assis ...

Exploring the power of Angular by implementing nested ng-repeat functionalities:

I am currently working on an ng-repeat feature to add items from the array (album array). Everything seems to be functioning correctly. However, I also have a colors array that should assign different background-colors to the card elements of the album arr ...

Using JavaScript to search JSON objects based on key value pairs

Consider a scenario where you have an array of objects in users.json: {"key":"userSubscriptions","value": [{"channel":"Netflix","user":"Bobby","region":"NA"}, [{" ...

The Controller is encountering an empty child array when attempting to JSON.stringify it

After examining numerous similar questions, I am uncertain about what sets my configuration apart. I've experimented with various ajax data variations and JSON formatting methods, but the current approach seems to be the closest match. This issue is ...

What is the method for setting a title within a for-loop when using vue.js in the given scenario?

<template v-for="item in job"> <tr> <td v-for="i in item.stage" :style="getStyle(i.status.name)" title="[[ i.node.name ]]" > <b>[[ i.node.name ]]</b> </td> </tr> </template> ...

Using environmental variables in Nuxt 3 outside of component setup scripts can be easily achieved by accessing the variables directly

I have stored different API URLs in my .env file, specifically for development and production environments. Here is how I access these URLs: const isProdEnv = process.env.NODE_ENV === 'production' const DEV_API_URL = "https://example-stage.h ...

How can one identify a concealed glitch that exclusively occurs for a particular individual or hardware in a React environment?

Is it possible to identify a bug that occurs only with a particular individual or hardware in a React application? This bug is invisible and never appears during tests, but only manifests with a specific client within my company. Do you have any tips on h ...

What is the method for looping through and inserting objects into an array using JavaScript's $.each function?

As a novice programmer, I am tackling the challenge of transferring four properties from my JSONP array into a new array for each item. $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { if (data.ok) { ...

What is the best way to create a unique custom control in Javascript, potentially utilizing jQuery?

My goal is to develop a custom control using JavaScript that includes methods, properties, and events, and can be rendered within a div element. For example, one such control could be a calendar. It would display in a div, with customizable properties for ...

How to implement a delay for submenu dropdown in Bootstrap 3

I am trying to implement a delay on a submenu that I have created, rather than the entire bootstrap3 dropdown menu. The goal is to allow users to easily move their cursor to the submenu without it closing unexpectedly. Although the jquery code should still ...

Having trouble populating the container with page content using AJAX, PHP, and JS?

Whenever I attempt to use the buttons to change the content, I keep receiving a 'There is no such page!' message. Below is the index.html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- ...