简体   繁体   中英

Sending multiple parameters to stored procedure with jQuery Ajax

I've got a web method that looks like:

[WebMethod]
        public void InsertDrugNameAndColorToDatabase(string drugName,string drugColor)
        {
            string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            using (var con = new SqlConnection(cs))
            {
                using (var cmd = new SqlCommand("spInsertDrugText", con))
                {
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@drugName", drugName);
                    cmd.Parameters.AddWithValue("@drugColor", drugColor);
                    cmd.ExecuteNonQuery();
                }
            }
        }

and a little JS:

<script type="text/javascript">
        $(document).ready(function () {
            $(".drugQuizzes").draggable({ tolerance: "fit" });
            $(".drugAnswers").droppable({
                drop: function (event, ui) {
                    var drugName = JSON.stringify({ "drugName": $(ui.draggable).find("span").text() });
                    var drugColor = JSON.stringify({ "drugColor": $(ui.draggable).css("background-color") });
                    console.log(drugColor);
                    console.log(drugName);
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "SendDrugName.asmx/InsertDrugNameToDatabase",
                        data: drugName,
                        dataType: "json",
                        success: function (data) {
                            //response(data.d);
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            console.log(xhr.status);
                            console.log(thrownError);
                        }
                    });
                }
            });
        });
    </script>
<script type="text/javascript">
        $(document).ready(function () {
            $(".drugQuizzes").draggable({ tolerance: "fit" });
            $(".drugAnswers").droppable({
                drop: function (event, ui) {
                    var drugName = JSON.stringify({ "drugName": $(ui.draggable).find("span").text() });
                    var drugColor = JSON.stringify({ "drugColor": $(ui.draggable).css("background-color") });
                    console.log(drugColor);
                    console.log(drugName);
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "SendDrugName.asmx/InsertDrugNameToDatabase",
                        data: drugName,
                        dataType: "json",
                        success: function (data) {
                            //response(data.d);
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            console.log(xhr.status);
                            console.log(thrownError);
                        }
                    });
                }
            });
        });
    </script>

I have a version of the stored procedure ans JS where only one parameter is sent to the stored procedure, and that works. From the console.log(drugName) and console.log(drugColor) I get

{"drugColor":"rgb(255, 69, 0)"} 
{"drugName":"ORACEA"}

How can I make the data parameter of the ajax call take multiple parameters at once? What are some names of general techniques that I need to be aware of for sending more than one parameter to a stored procedure at once using jQuery ajax?

您可以指定多个数据项,例如:

data: 'drugName='+ drugName  + '&drugColor=' + drugColor;

You don't need to stringify it at all, you can pass the parameters as an object. Try this:

$(".drugAnswers").droppable({
    drop: function (event, ui) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "SendDrugName.asmx/InsertDrugNameToDatabase",
            data: {
                'drugName': $(ui.draggable).find("span").text(),
                'drugColor': $(ui.draggable).css("background-color")
            },
            dataType: "json",
            success: function (data) {
                //response(data.d);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }
        });
    }
});

The ajax() function will then stringify it for you and pass it across to your C# endpoint.

Consider building an object literal on the client-side and passing that entire object to the service, thus you have one parameter in your service call, like this:

Client-side:

var myData = {};
myData.DrugName' = $(ui.draggable).find("span").text();
myData.DrugColor' = $(ui.draggable).css("background-color");

// Create a data transfer object (DTO) with the proper structure, which is what we will pass to the service.
var DTO = { 'theData' : myData };

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "SendDrugName.asmx/InsertDrugNameToDatabase",
    data: JSON.stringify(DTO),
    dataType: "json",
    success: function (data) {
        //response(data.d);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr.status);
        console.log(thrownError);
    }
});

Now on the service-side, you will need to build a class that represents the contents of the object literal created above, like this:

public class ServiceData
{
    public string DrugName { get; set; }
    public string DrugColor { get; set; }
}

Finally, change your web service code to accept one parameter, like this:

[WebMethod]
public void InsertDrugNameAndColorToDatabase(ServiceData theData)
{
    string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
    using (var con = new SqlConnection(cs))
    {
        using (var cmd = new SqlCommand("spInsertDrugText", con))
        {
            con.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@drugName", theData.DrugName);
            cmd.Parameters.AddWithValue("@drugColor", theData.DrugColor);
            cmd.ExecuteNonQuery();
        }
    }
}

Note: The data passed from the jQuery call is automatically matched up with the class properties you have in your ServiceData class as long as the names match on both the client-side and server-side.

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