What is the best way to run a function on a repository in asp.net mvc?

I encountered a similar issue in the past, but the solution I used back then doesn't seem to work here. I am attempting to trigger an overloaded repository function to organize my view data based on the selected option from the dropdown menu.

I utilized the "onchange" event to run my JavaScript code, but I am struggling to call the repository function due to mismatched overloads and uncertainty about how to properly bind them together. Any assistance provided would be highly appreciated.

HTML View Code

<select id="sortSelect" onchange="CallChangeFunction()">
    <option value="default">Default</option>
    <option value="make">Make</option>
    <option value="model">Model</option>
    <option value="year">Year</option>
</select>

<script>
    function CallChangeFunction(val) {
        alert("Perform sorting action here!");
    }
</script>

Listing Repository Code

IEnumerable<ListingStat> GetListingStats(int inCompanyID, int inMonth, int inYear);


public IEnumerable<ListingStat> GetListingStats(int inCompanyID, int inMonth, int inYear)
{
    //var x = document.getElementById("sortSelect").value;

    // Query might be optimized using Entity Framework.. However, there are no direct keys between listingstats and makemodel stats, and creating them solely for EF purposes is not ideal
    var theSQL = "select d.DatePK, ls.*, " +
                 "mm.Make as MM_Make, mm.Model as MM_Model, mm.ListingsThatWereActive as MM_ListingCount, mm.MedianPriceExcludeZero as MM_MedianPrice, mm.PopularityRank as MM_PopularityRank, " +
                 "mm.PopularityMaxRank as MM_PopularityMaxRank, mm.AverageFavorites as MM_Favorites, mm.AverageSearchImpressions as MM_SearchImpressions, mm.AverageBuyerInquiries as MM_BuyerInquiries, mm.AveragePhoneInquiries as MM_PhoneInquiries, mm.AverageListingViews as MM_ListingViews, " +
                 "ymm.SupplyDemandIntegerPercentile as YMM_SupplyDemandPercentile, ymm.TotalListingViews as YMM_TotalListingViews " +
                 "from " +
                 "PerformanceDataMart.Dates d " +
                 "left outer join PerformanceDataMart.ListingStats ls on ls.DateFK = d.DatePK and ls.CompanyId = :CompanyID " +
                 "left outer join PerformanceDataMart.MakeModelStats mm on mm.DateFK = d.DatePK and mm.Make = ls.Make and mm.Model = ls.Model and mm.Year is null " +
                 "left outer join PerformanceDataMart.MakeModelStats ymm on ymm.DateFK = d.DatePK and ymm.Make = ls.Make and ymm.Model = ls.Model and ymm.Year = ls.Year " +
                 "where d.Month = :Month and d.Year = :Year";

    var theDB = new CCDB();

    List<ListingStat> theList = new List<ListingStat>();

    using (IDataReader aDR = theDB.OpenDataReader(theSQL, inCompanyID, inMonth, inYear))
    {
        while(aDR.Read())
        {
            ListingStat theListingStat = new ListingStat();
            theList.Add(theListingStat);

            theListingStat.ListingId = As.Integer(aDR["ListingId"]);
            theListingStat.Year = As.Integer(aDR["Year"]);
            theListingStat.Make = As.String(aDR["MM_Make"]);
            if (theListingStat.Make == "")          
                theListingStat.Make = As.String(aDR["Make"]);

            theListingStat.Model = As.String(aDR["MM_Model"]);
            if (theListingStat.Model == "")
                theListingStat.Model = As.String(aDR["Model"]);
        }
    }

    return theList;
}

Answer №1

Add JQuery to your page and experiment with this code snippet:

<script>
    $(function () {
        $("#sortSelect").change(function () {
            alert("This is just a test.");
        });
    });
</script>

Answer №2

Make sure to maintain the order and data types of the parameters in your ajax call identical to those in your overloaded controller function.

Your function should resemble the following:

function FetchListingData(companyID, month, year) {
    var model = {
        "companyID": companyID,
        "month": month,
        "year": year
    };
    $.ajax({
        url: "/YourControllerName/YourMethodName",
        type: "Post",
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            // perform actions after calling the controller
        },
        error: function (data) {
            // handle errors
        }
    });
}

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

Utilizing jQuery/AJAX to interact with database in Django

Seeking assistance as I've tried multiple times with little success. Using the tango with Django book and various online examples, but no luck. Currently designing a 'Fake News' website with Django featuring a mini-game where users vote on w ...

A collection of strings where each item is unique

I have a binding list to a repeater in ASP.NET. Currently, it is displaying like this: https://i.sstatic.net/6CgUE.png But I want it to display like this: https://i.sstatic.net/3eUI3.png Here's my code: <asp:Repeater ID="RptID" runat="server" ...

Tips for clearing state when simply refreshing a DataTable on the page

When it comes to a datatable on a page, I am facing a unique challenge. I want the datatable to be refreshed with a clear state (no column order, etc.), but if the page is accessed by pressing the back button, it should retain its state. I have experiment ...

Vue.js has mysteriously stopped functioning

My Vue.js project suddenly stopped working and I've been trying to figure out the issue for hours with no luck. Here's an overview of my HTML file which includes dependencies and a table displaying data from users. <!DOCTYPE html> <html ...

Issue with C# Entity Framework not recognizing Foreign Key attribute

Currently, I am working with "User" and "Product" entities where the product has a foreign key to the user (UserId -> User). I am attempting to add another foreign key to the user in the product entity, but I am encountering issues with the migration pr ...

I encountered an error message stating "Unexpected token {" while trying to import the module "express-fileupload"

Struggling to implement file uploading with NodeJS on Ubuntu, encountering errors. Upon adding const fileUpload = require('express-fileupload'); the app fails to compile, throwing this syntax error: 2|theproje | /home/asgeir/nodejs/first_test ...

Browser lacks proper credentials for passport authentication

I'm currently learning how to incorporate user authentication using passport.js. I have successfully set up a basic passport "local" strategy on the server side, along with a single POST route for logging in users. When testing with insomnia, everythi ...

I love the flexibility that webpack provides when it comes to using aliases to override existing dependencies in the node_modules folder

When using Webpack 4, I'm looking to replace the rsg-components from node_modules with my own version. By doing this, react-styleguidist should then import my customized component instead. It seems that resolve.alias doesn't have priority over ...

A simple guide to running Express Js and MongoDB from the command line and gracefully closing the terminal

Is there a way to run an Express project without the terminal being visible or easily closed? I need my server to stay running, but I don't want the user on the local PC to be able to see or close the terminal. Any suggestions on how to achieve this ...

How can I integrate NIB into a project created with WebStorm 8 using node.js, Express, Jade, and Stylus?

Starting off with node.js, Express, Jade, Styl and NIB in WebStorm 8 has been a bit of a challenge. Unfortunately, WebStorm does not natively support NIB, so I have been looking into how to manually add it. Here is the sample app.js generated by WebStorm: ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

Utilizing jQuery to invoke a function at the conclusion of another function's execution

Can someone explain how jQuery can achieve the following? $('.test').css().otherThing...... etc I'm attempting to accomplish this with prototype: var myPrototype = function () {}; myPrototype.prototype.console1 = function() { console.lo ...

Define the content and appearance of the TD element located at the x (column) and y (row) coordinates within a table

In my database, I have stored the row and column as X and Y coordinates. Is there a straightforward way to write code that can update the text in a specific td element within a table? Here is what I attempted: $('#sTab tr:eq('racks[i].punkt.y&a ...

Is there a way to open an image.png file in typescript using the "rb" mode?

Is there a way to open png files in typescript similar to the python method with open(path+im,"rb") as f:? I have a folder with png files and I need to read and convert them to base 64. Can anyone assist me with the equivalent method in typescript? This i ...

What is the method for obtaining the worldwide location of a vertex on a skinned mesh in Three.js?

In the realm of Three.js, we've recently acquired the ability to determine the global position of a vertex in a non-skinned mesh thanks to insights from this question. Now, the query arises - how can one ascertain the global position of a vertex in a ...

What is the best way to obtain the output produced by a function when a button is clicked

When I click on a button, the desired action is to trigger a function that adds a new property inside an object within a large array of multiple objects. This function then eventually returns a new array. How can I access and utilize this new array? I am ...

Is there a way to reset the dynamic flexslider when a click event occurs?

Seeking a way to refresh the flexslider on a click event. I have embedded the flexslider in a Bootstrap pop-up and need it to update when the user clicks. The issue arises when I try to refresh the slider as it fails to display properly, likely due to losi ...

Unable to resolve issue with Display:flex in my CSS, despite numerous attempts

Here is the structure of my CSS and HTML: #TopBar{ display: flex; justify-content: space-between; z-index: 1; position: fixed; top: 0px; left: 0px; background-color: rgb(25,25,25); height:115px; width: 2000px; } #Logo{ top: 0px; height: 110px ...

Is there a method to add HTML code statically rather than in a dynamic environment?

I'm currently in the process of developing a front-end website with no backend code, as I plan to host it on GitHub pages. I feel that adding any additional backend functionality would be unnecessary. Is there a simple method to incorporate common el ...

What is the best way to execute the app functions, such as get and post, that have been defined

After creating a file that sets up an express middleware app and defines the app function in a separate file, you may be wondering how to run the app function. In your app.js file: const express = require('express') const cors = require('c ...