Using a javascript parameter in a cshtml file to filter data in a datatable

Here is the model code

public class viewCase
{
  public List<string> lstCategory   { get; set; }
  public DataTable dtWrkTsk { get; set; }
}

This is the controller code

string query = "SELECT WorkFlowID,Subject,Category FROM CMSTasksWorkFlow" 

objcase.dtWrkTsk   = objdataclas.ExecuteDataTable(query);

return View("../ViewCases/CasesScreen",objcase);

Below is the cshtml code snippet

 function getCaption() {

var cat=    $("#layout option:selected").text();  

var arr =  @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(
Model.dtWrkTsk.Select("Catagory='" + cat + "'") )); 
}

An error 'cat ' does not exist in current context' is encountered

If trying this approach

function getCaption() {

      var cat=    $("#layout option:selected").text();  
     var arr =  @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(
       Model.dtWrkTsk.Select("Catagory='" +@<text> cat </text> + "'") ));}  

Error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type

<div id="addTask" class="modal fade " aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content round">
                <div class="modal-header"><h4>New Task </h4></div>
                <div id="tbody" class="modal-body" style="height:20%">
                    @Html.DropDownList("layout", Model.lstCategory.Select(m => new SelectListItem { Text = m, Value = m }), "All", new { onclick = "getCaption()" })
                    <div id="dtask" style="width: 80%; overflow: scroll; ">

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-primary"  >OK</button>
                    <button type="button" data-dismiss="modal" class="btn">Cancel</button>
                </div>
            </div>
        </div>
    </div>

The goal is to keep the datatable disconnected from the server. The getCaption() function is called whenever the user changes the value in the Html.DropDownList.

Only the select condition in the datatable needs to be updated based on the JavaScript variable being passed.

How can the JavaScript variable be passed in the datatable.select function?

Answer №1

When using @Html.Raw() in the code snippet var arr = @Html.Raw(...), it's important to note that this is razor code that gets processed on the server before being sent to the view. The code includes a query function .Select() which relies on a JavaScript variable that may not be in scope at that point.

To resolve this issue, you should assign the collection to a JavaScript variable and then filter the resulting array in JavaScript based on the selected option.

In the scenario where dtWrkTsk represents a collection of a model with a property string Category, and you want to filter the collection to only return objects whose Category value matches the selected option:

@Html.DropDownList("layout", Model.lstCategory.Select(m => new SelectListItem { Text = m, Value = m }), "All")

Alternatively:

@Html.DropDownList("layout", new SelectList(Model.lstCategory), "All")

<script>
    // Assign the collection to a JavaScript array
    var arr = @Html.Raw(Json.Encode(Model.dtWrkTsk))
    $('#layout').change(function() {
        var selectedCategory = $(this).val();
        // Filter the collection for matching objects
        var result = $(arr).filter(function(index, item) {
            return item.Category === selectedCategory;
        });
        .... // Perform actions with the results
    });
</script>

For further information, consider reading about Unobtrusive JavaScript.

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

Tips for transferring a file to PocketBase using NodeJs

Currently, I am in the midst of a project that necessitates uploading numerous PDF files to a PocketBase collection. All the necessary files are saved on my computer and my goal is to upload them using nodejs along with the PocketBase JavaScript SDK. Howe ...

Sending chosen choice to controller method

I'm working with a table that contains inputs and angular models. <td> <select class="form-control" id=""> <option ng-model="mfrNo" ng-repe ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...

Navigating through segments of an array in javascript

Within my condensed array, I have omitted most of the input data to demonstrate a particular task. For illustrative purposes, here is an extensive example showcasing the elements: storyArray=["#C1", "String showing first message", "String displaying secon ...

Error message: Unable to locate local module in node.js subdirectory

Exploring the folder structure within my application https://i.stack.imgur.com/Pkxpg.png Referring to app_modules/bar and app_modules/foo as local modules Root Folder package.json "dependencies": { "body-parser": "~1.18.2", "cookie-parser": "~ ...

EJS files do not show variables passed from Node

I am currently developing a 'preferences' section on my website, where users can make changes to their email addresses and passwords. Within this preferences page, I aim to showcase the user's current email address. router.get("/settings", ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

The calculator is experiencing issues with JavaScript functionality

Having some trouble developing a calculator using HTML5, CSS, and JavaScript. After passing my HTML and CSS through validators successfully, I encountered issues when adding JavaScript functions to enable the functionality of the buttons on the calculator. ...

Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended. ↓ The current implementation is not effective and needs improvement import React, { useState, useEffect } from 'react'; const Li ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

How to use the v-model to round up a number in Vue.js

I need to round up a number in my input field: <b-form-input id="amount_input" type="number" v-model="Math.ceil(form.contract.reward_cents / 100)" :state="validate(form.contract.reward_cents)"/> ...

Exploring the functionality of arrays within Selenium IDE

Recently delving into Selenium IDE, I am a beginner and looking for guidance. The challenge at hand: How can I access values from an array generated by execute script | var array1 = document.getElementsByClassName("Post"); return array1; | array1 Initi ...

Tips for converting numbers in JavaScript and troubleshooting issues when trying to filter out non-numeric characters using Tel input commands

After finding this answer on how to convert digits in JavaScript, I attempted to apply the method to convert numbers in a phone number field with tel input type. function toEnglishDigits(str) { const persianNumbers = ["۱", "۲", &quo ...

Passing data from child to parent in Angular using EventEmitter

I have integrated a child grid component into my Angular application's parent component, and I am facing an issue with emitting data from the child to the parent. Despite using event emitter to transmit the value to the parent, the variable containing ...

Importing information from the Document Object Model in Vue.js, focusing on the action attribute of a form

Can Vue be used to create a binding where the data item in the Vue instance is initialized from the DOM? In my specific case, I want my Vue instance to receive the action attribute of a form element. For example, this is how my HTML would look like (the ...

The functionality of the AngularJS nested router is not functioning properly

I am encountering some challenges with Angular routing, specifically when using nested routes: The current 'abc' state works flawlessly for the route /admin/team/:teamId .state('admin', { url: '/admin', controller: & ...

What options do I have for personalizing this Google Bar Graph?

I am currently working on creating a Google bar chart. You can view my progress here: http://jsfiddle.net/nGvdB/ Although I have carefully reviewed the Google Bar Chart documentation available here, I am struggling to customize the chart to my needs. Spec ...

updating rows in a table

Currently, I have a grid array filled with default data retrieved from the database. This data is then displayed on the front end in a table/grid format allowing users to add and delete rows. When a row is added, I only want to insert an empty object. The ...

Selection of Dropdown results in PDF not loading

I am facing an issue with my function that selects a PDF from a dropdown list. Instead of loading and displaying the PDF, it only shows a blank modal. Any suggestions on how to fix this? <li> <a href="">Case Studies</a> <ul clas ...

Passing a particular object from an array of objects as props in React Native

Suppose you have a static array consisting of 4 objects and the goal is to pass specific data items from the third object in this array. How can this task be accomplished? Let's consider an example: const ENTRIES = [ { name: "John" color: "#fffff" f ...