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

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...

Encountering an unexpected token ';' in a random generator while attempting to utilize an if-else statement for determining DOM manipulation

After dabbling in programming on and off for a few years, I've finally decided to dive deep with some simple personal projects. One of the tasks I'm working on is creating a randomizer for a pen and paper RPG, where it samples from an array at ra ...

Is there a way to resolve the issue of my localStorage getting overridden on page refresh?

I am currently working on a simple React app and encountering an issue with the localStorage. Whenever I refresh the page, the todo list stored in the localStorage disappears. How can I ensure that the todos remain visible even after a refresh? Any sugges ...

Hidden Password Field Option in HTML

My HTML password textbox has the input type set as password, but I can still see what is being typed. This shouldn't happen as password inputs should be masked. Can someone please advise me on how to resolve this issue? To replicate, copy the code be ...

Customize date filtering in KendoUI grid

I am trying to modify the date format in the filter of my kendo grid. For example, I would like to change 1/30/2015 to Jan 30, 2015 I have successfully changed the date format for Start Date field: "StartDate", title: " ...

Asynchronous task during stream processing

Can anyone assist me? I am looking to read a file as a stream and when processing the initial chunk, I need to create a database table in an async manner. To achieve this, I want to develop a duplex/transformer stream that would be responsible for creatin ...

What is the best way to apply a background image to a DIV element using CSS

The main aim is to change the background image of a DIV using AJAX. $.getJSON("https://itunes.apple.com/search?term=" + searchTerm + '&limit=1' + '&callback=?', function(data) { $.each(data.results, fun ...

In React, facing difficulty in clearing setTimeout timer

After clicking the button, I want my code to execute 3 seconds later. However, I'm having trouble achieving this. It either runs immediately or doesn't stop running. <Button onClick={setTimeout(() => window.location.reload(false), 4000), cl ...

What is an alternative way to display static images in Rails 5 without relying on the Asset Pipeline?

I developed a web-based application with the backend built on Rails 5. Utilizing AngularJS for the frontend, I opted to not use the Asset Pipeline to deliver static content. Instead, I loaded all my scripts (JS & CSS) in the index.html file located within ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

Can you retrieve data or HTML content from the main Vue 3 component?

I have experience using Vue in previous projects but I'm currently facing some challenges on how to pass information/arguments to a root Vue 3 component. My goal is to set up something like this in my HTML: <div class="nav-app" nav=&quo ...

Leveraging the power of jQuery/javascript in conjunction with Google Forms

Currently, I am attempting to utilize jQuery and JavaScript with an iframe that contains a Google form. The code snippet is displayed below: <body> <iframe id="myFormFrame" src="https://docs.google.com/forms/d/smfjkafj809890dfafhfdfd/viewform?emb ...

Creating a specialized JSON serializer that is not automatically triggered

I am currently using Newtonsoft JSON.Net and I would like to include custom attributes that can be handled by a specific JSONConverter. The current method to achieve this includes using [JsonConverter(typeof(CustomJsonConverter))]. However, I only want thi ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

Troubleshooting the Confirm Form Resubmission problem on my website

Hello everyone! I'm working on a website and facing an issue where refreshing the page triggers a confirm form resubmission prompt. Could someone please advise me on how to resolve this? Thank you in advance! ...

One way to achieve the same functionality as onclick in an Ajax call using

I have two JSPs. In the first JSP, I am making an ajax call and receiving data (Ajax body) from the second JSP. However, I am unsure of how to execute jQuery when an argument is present in the function. Everything works fine without an argument. In the ...

Avoid receiving a 404 error when using an invalid ID

When trying to set up my workoutId param, I encounter the following error: UnhandledPromiseRejectionWarning: CastError: Casting to ObjectId failed for value "5fb02bd8b61abc02" at path "_id" for model "Workout" If the workou ...

Having trouble initiating NPM in a terminal

I keep encountering an issue whenever I try to start NPM using a command in the terminal. Here is the error message that appears: npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark your favorite packages npm ERR! npm stars # Vi ...

Is there a specific requirement for importing a React component into a particular file?

I am facing an issue with my component and two JavaScript files: index.js and App.js. When I import the component into index.js, it displays correctly on the screen. However, when I import it into App.js, nothing appears on the screen. Here is the code fr ...

Generating a client-side MD5 hash for an image file in order to compare it to the hash calculated by Firebase?

Is there a way to calculate the MD5 of an image file on the client side within my Angular Map application, that will match the MD5 when I store the file on Firestore? I need to verify that a user's file matches a reference version stored in Firebase ...