Connecting a GridView to a database in MVC 5 using C# while utilizing ajax JavaScript techniques

I am struggling with creating a grid without using Kendo. I am trying to build a dictionary where I have a list of words that I pass to an AJAX JavaScript and display it in a grid on the view. However, I am having trouble figuring out how to make this work. Any help would be greatly appreciated.

This is my controller:

public ActionResult CheckingInBank(string username, string password, string datasource, string bnkname, string SqlQuery)
{
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder["Server"] = datasource;
    builder["Connect Timeout"] = 1000;
    builder["Trusted_Connection"] = true;
    builder["Integrated Security"] = false;
    builder.InitialCatalog = bnkname;
    builder.Password = password;
    builder.UserID = username;

     List<TranslateViewModel> translateViewList = new List<TranslateViewModel>();
    WebGrid TranslateGrid = new WebGrid();

    using (SqlConnection con = new SqlConnection(builder.ConnectionString))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand(SqlQuery, con))
        {
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    TranslateViewModel translateView = new TranslateViewModel();
                    translateView.id = dr[0].ToString();
                    translateView.word = dr[1].ToString();
                    translateView.translate = dr[2].ToString();

                    translateViewList.Add(translateView);
                }
                if (translateViewList.Count > 0)
                {
                    return Json(new { translateViewList = translateViewList }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("No Record Found");
                }
            }
        }
    }
}

JavaScript

function checkingInBank() {
    var translate = $("#eWord").val();
    var bnkname = $("#combo").val();
    var username = $("#Username").val().trim();
    var password = $("#password").val();
    var datasource = $("#Datasource").val();
    var SqlQuery = "select * from lego.LocalizationView  where Word =N'" + translate + "'";
    if (bnkname) {
        $.ajax({
            url: 'Home/checkingInBank?' + "Username=" + username + "&Password=" + password + "&databaseConString=" + datasource + "&bnkname=" + bnkname,
            data: {
                bnkname: bnkname,
                username: username,
                password: password,
                datasource: datasource,
                SqlQuery: SqlQuery
            },
            type: "get",
            datatype: "json",
            traditional: true,
            success: function (data) {
                console.log('I am facing some challenges with this');
                debugger;
                if (data != "No Record Found") {
                     $('#gridContent').html(data);
                } else {
                   alert('No Record Found');
                }
            }
        });
    }
    else {
        //do nothing
    }
}

and my view

and this :(((

@{
    var grid = new WebGrid(ViewModeList, canPage: true, rowsPerPage: 5,
                      selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
    grid.Pager(WebGridPagerModes.All);
}
@grid.GetHtml(
tableStyle: "webGrid",
columns: new[]
{
    grid.Column("id"),
    grid.Column("Word"),
    grid.Column("Translate")
});

Answer №1

It is crucial to never transmit sensitive data such as database credentials and SQL queries from client-side JavaScript to the server. Exposing this information can lead to unauthorized access to your database, allowing malicious users to execute destructive commands like

var SqlQuery = "TRUNCATE TABLE lego.LocalizationView"

Furthermore, there seems to be a misunderstanding in how WebGrid is utilized. For instance, if your controller method returns JSON data but is being inserted into an HTML element in the JavaScript code:

$('#gridContent').html(data);

Additionally, it's important to ensure that your controller action is appropriately decorated with the HttpGet attribute.

I recommend seeking out and implementing a functional example of utilizing WebGrid with AJAX requests; for instance, you could refer to a resource I found: link

In the provided example, Entity Framework is employed to connect to the data source. However, you could start by returning static JSON data in your controller method to verify the functionality before integrating with your own database:

[HttpPost]
public JsonResult AjaxMethod(int pageIndex)
{
    CustomerModel model = new CustomerModel();
    // Code snippet demonstrating static JSON data
}

Once you have successfully replicated this setup, you can adapt the CustomerModel class to suit your requirements, adjust the HTTP method, establish a connection to your database, and make necessary modifications to the grid columns.

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

Step-by-step guide on resolving AngularJS Issue: [$injector:modulerr]

I'm encountering an issue with Angular JS where I'm receiving the following error: jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to: Error: [$injector:nomod] Module 'application' is no ...

Page Loading Issue: Unable to Process Ajax POST Request

I am facing an issue with my form that uses Ajax to send data to a PHP file. Everything seems to be working fine as the data sends properly, but I keep getting an "Error loading page" message when using jQuery Mobile. HTML File <div data-role="page" i ...

What is the best way to implement dynamic variables in ng-model-options?

I am experiencing an issue with the ng-model-options not updating as expected. For instance, if you input 4:00 pm in both time fields in the snippet below, you'll notice that the UTC output differs - the first is 6 and the second is 8. This behavior i ...

If the ID matches a value in the list, assign a class to the div

Hello, I am looking for assistance on how to add a class to a div if its id matches a value from a predetermined list: list = ["a1", "a2", "a3"] <div id="a1"></div> <div id="b1"></div> <div id="c1"></div> <div id=" ...

Turn off error notifications from eslint parsing

Within my code, there is a conditional export that looks like this: if (process.env.NODE_ENV === 'testing') export myFunc; While in es6, this type of statement is typically not allowed due to the requirement for imports and exports to be top- ...

The response from AJAX is successfully retrieved, however, the HTML code within the response is not being appended to the

html: <form method="POST"> <input type="text" name="input1" id="input1"> <input type="text" name="input2" id="input2"> <button type="button" onclick="checkInputs()">OK</button> </form> <div id="display_panels">< ...

What happens when ES6 async/await interacts with Observables and streams during failures?

Recently, I attempted to reproduce this code from a GitHub repository (link provided). It worked as intended, but I encountered an issue with unhandled promise warnings. Where should I place the catch statement in a situation like this, if necessary? Are ...

How to use Angular ngRepeat to create multiple select fields that do not show previously selected data with ng-options

Looking at the issue from a high level; I'm fetching data from an api and creating a CRUD page for it. The user can choose from a set of labels provided in the data. Here is a code snippet illustrating my dilemma. The selected labels are denoted by t ...

What is the method for printing a webpage that has been modified using JavaScript?

Take a look at this screenshot to see what I'm working with. Users have the ability to modify the page by removing items, adding new items, or marking items as complete by crossing them out. I want users to be able to print the altered page using Jav ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

I'm receiving a Reference Error stating that 'next()' is not defined, despite the fact that I have defined it in my JavaScript code. What could be causing this issue?

I have a javascript function called next() to process information and then call the function from HTML. However, my Firefox console is showing a ReferenceError: 'next' is not defined. I am aware that there is an error in my code, but I cannot pin ...

A step-by-step guide on setting --max-old-space-size using the npm link command

Can the --max-old-space-size parameter be configured using npm link? I am aware that it can be set using the node command such as node --max-old-space-size=, but I am attempting to achieve the same result through the npm link command. Is this feasible? Yo ...

Separate a string into substrings based on the number of spaces it contains

My goal is to split a string into multiple parts based on spaces, resulting in an array with 3 values. For instance, if I have the string "SIZZLING STEAK TERIYAKI BOY" and divide it into 3 parts, the output should be ["SIZZLING STEAK", "TERIYAKI", "BOY"]; ...

Is there a way to prevent the ENTER key on the keyboard from interacting with

When visiting http://api.jqueryui.com/datepicker/, I came across the following information: Keyboard interaction While using the datepicker, various key commands are available: PAGE UP: Move to the previous month. PAGE DOWN: Move to the next month. CTRL ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

Determine the shared elements between two distinct arrays and create an object that includes these common elements

I am dealing with 2 different arrays of objects var array1 = [ {id: 1, name:'fruit', rating:5}, {id: 4, name:'vegetable', rating: 3}, {id: 8, name:'meat', rating:1} ]; var array2 = [ {alimentId: 1, quantity: 2}, {alimentId: 4 ...

Unable to trigger click event following regeneration of elements

I am having trouble with a click event on checkboxes when I remove and insert new table bodies. How can I fix this issue? I have tried using append(), clone() but it didn't work for my code. To demonstrate the problem, I have created a JSFIDDLE which ...

I am attempting to verify a user's login status with Next.js and Supabase, however, I am encountering difficulties in making it function properly

I recently cloned this repository from https://github.com/vercel/next.js/tree/canary/examples/with-supabase-auth-realtime-db and I'm trying to implement a navigation bar that changes based on the user's login status. Unfortunately, the code I&ap ...