简体   繁体   中英

Getting SQL Data from Dropdown onChange event using ASP.NET Core v2 and Razorpages

I have a dropdown box populated from SQL using C#. When the user select an entry in the dropdown box I need to run a SQL query based on the selected item and populate some other input fields with the resultset from SQL.

Think of it as a list of customers, when selecting a customer the input fields are populated with default values for the customer, such Address, City etc which later can be changed by the user.

My first thought was to use an ajax call on the dropdown onchange event but don't know from where I should get the MSSQL data? is it possible to retrieve data from SQL from an URL? or can I bind the dropdown to the onchange event with C# and add the query data to a script block from C#?

What is a good approach for solving this?

I am using ASP.NET Core v2 with Razorpages

在此处输入图片说明

Thanks

Thomas

You should use ajax. Create an ajax call like this:

var dataToPost = {customer: "custumerValue", additionalData: "something"};
$.ajax("{path to controller}/GetData", {
    method: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(dataToPost)
}).done(function (data) {
    //set properties
    console.log(data.value1);
    console.log(data.value2);
}).fail(function () {
    //error
});

and in your controller create a function:

public virtual JsonNetResult GetData(string customer, string additionalData)
{
    // Get data

    return new JsonNetResult()
    {
        Data = new
        {
            value1 = "something",
            value2 = "something"
        }
    };
}

Make sure you specify the correct path to your controller, if your controller is named CustomerController you should only insert Customer in the url. Also the name of the function and the parameters must match the names used in the ajax call.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM