如何从Gridview的下拉列表中获取值,然后通过ajax和jquery将其传递给我的Web服务?

时间:2019-04-30 10:07:40

标签: jquery html ajax web-services

我试图从下拉列表中选择值,然后将其保存到数据库中。我需要将propid和状态传递给Web服务,以便代码运行。

下面,我在下拉列表中添加了代码,并在其中显示了jquery和ajax的代码,在这些代码中,我尝试获取值并将其传递到Web服务上

    </div>


<script>
            $("[id*= ddl_status]").on("change", function () {

        var status = $(this).val();
        $drop = $(this);
        $check = $drop.closest().find('[id*= Idtbl_property]');
                $id = $check.val();
                alert(drop);
        $.ajax({
            type: "POST",
            url: "/webservices/recordStatusChange.asmx/SaveChange",
            data: '{propid:' + $id + ',status:' + status +  + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert("Thank you for providing your input");
                $("[id*= ddl_Reason]").hide();
            }
        }).fail(function (error) {
            alert(error.StatusText);
        })

    });
</script>

            <div class="content">
<asp:GridView ID="gridview_leads" runat="server" CellPadding="3" CellSpacing="1" 
    Font-Names="Arial" Font-Size="Small" AutoGenerateColumns="False" OnRowUpdating="gridview_leads_RowUpdating">
<Columns>

    <asp:BoundField DataField="Idtbl_property" HeaderText="Property ID" >
    <ItemStyle Font-Size="Small" />
    </asp:BoundField>

    <asp:BoundField DataField="ClientName" HeaderText="Client Name" >
    <ItemStyle Font-Size="Small" />
    </asp:BoundField>

    <asp:BoundField DataField="ClientEmail" HeaderText="Client Email" >
    <ItemStyle Font-Size="Small" />
    </asp:BoundField>

    <asp:BoundField DataField="ClientCell" HeaderText="Client Cell" >
    <ItemStyle Font-Size="Small" />
    </asp:BoundField>

            <asp:TemplateField ShowHeader="True" HeaderText="Status">
        <ItemTemplate>      
          <asp:DropDownList ID="ddl_status" runat="server"  OnInit="ddl_status_Init"></asp:DropDownList>
        </ItemTemplate>
         <ControlStyle Font-Names="Arial" Font-Size="Small" />
        <ItemStyle BackColor="#FFFFCC" Font-Names="Calibri" Font-Size="Small" />
    </asp:TemplateField>


    </Columns>
                                 </asp:GridView>

1 个答案:

答案 0 :(得分:0)

这有效。

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm5SO.aspx.cs" Inherits="FredWebForm.WebForm5SO" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".ddlStatusClass").change(function () {
                //webforms makes you do this
                var propertyId = $(this).closest('td').prev('td').prev('td').prev('td').prev('td').text();
                var status = $(this).val();
                $.ajax({
                    type: "POST",
                    url: "recordStatusChange.asmx/SaveChange",
                    //took out contenttype
                    //contentType: "application/json; charset=utf-8",
                    data: { propertyId: propertyId, status: status },
                    dataType: "json",
                    success: function (response) {
                        alert(response);
                        alert("Thank you for providing your input");
                        //$("[id*= ddl_Reason]").hide();
                    },
                    //changed your error
                    error: function (request, status, error) {
                        alert("error");
                        alert(error);
                    }
                })
            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <%--added event onrowdatabound--%>
            <asp:GridView ID="gridview_leads" runat="server" CellPadding="3" CellSpacing="1"
                Font-Names="Arial" Font-Size="Small" AutoGenerateColumns="False" OnRowDataBound="gridview_leads_RowDataBound">
                <Columns>
                    <asp:BoundField DataField="Idtbl_property" HeaderText="Property ID">
                        <ItemStyle Font-Size="Small" />
                    </asp:BoundField>
                    <asp:BoundField DataField="ClientName" HeaderText="Client Name">
                        <ItemStyle Font-Size="Small" />
                    </asp:BoundField>
                    <asp:BoundField DataField="ClientEmail" HeaderText="Client Email">
                        <ItemStyle Font-Size="Small" />
                    </asp:BoundField>
                    <asp:BoundField DataField="ClientCell" HeaderText="Client Cell">
                        <ItemStyle Font-Size="Small" />
                    </asp:BoundField>
                    <asp:TemplateField ShowHeader="True" HeaderText="Status">
                        <ItemTemplate>
                            <%--took out OnInit="ddl_status_Init"  --%>
                            <asp:DropDownList ID="ddl_status" CssClass="ddlStatusClass" runat="server"></asp:DropDownList>
                        </ItemTemplate>
                        <ControlStyle Font-Names="Arial" Font-Size="Small" />
                        <ItemStyle BackColor="#FFFFCC" Font-Names="Calibri" Font-Size="Small" />
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

后面的代码:

public class BindingObjectSO
{
    public string Idtbl_property { get; set; }
    public string ClientName { get; set; }
    public string ClientEmail { get; set; }
    public string ClientCell { get; set; }
}
public partial class WebForm5SO : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ArrayList list = new ArrayList();
            list.Add(new BindingObjectSO { ClientCell = "ClientCell1", ClientEmail = "ClientEmail1", ClientName = "ClientName1", Idtbl_property = "IdProp1" });
            list.Add(new BindingObjectSO { ClientCell = "ClientCell2", ClientEmail = "ClientEmail2", ClientName = "ClientName2", Idtbl_property = "IdProp2" });
            list.Add(new BindingObjectSO { ClientCell = "ClientCell3", ClientEmail = "ClientEmail3", ClientName = "ClientName3", Idtbl_property = "IdProp3" });
            gridview_leads.DataSource = list;
            gridview_leads.DataBind();
        }
    }
    protected void gridview_leads_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var ddl = e.Row.FindControl("ddl_status") as DropDownList;
            if (ddl != null)
            {
                ddl.DataSource = new List<string>() { "0", "1", "2", "3", "4" };
                ddl.DataBind();
            }
        }
    }
}

Web服务:

/// <summary>
/// Summary description for recordStatusChange
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class recordStatusChange : System.Web.Services.WebService
{
    [WebMethod]
    //made method void
    public void SaveChange(string propertyId, string status)
    {
        //put breakpoint here
        var propId = propertyId;
        var stat = status;
        //asmx usually return xml, so you can change dataType: "json", to "xml"
        //or do what I did following to get json back from ws
        HttpContext.Current.Response.ContentType = "application/json";
        var myJSON = "{'type':'Success'}";
        //get JSON NewtonSoft nuget
        HttpContext.Current.Response.Write(JsonConvert.SerializeObject(myJSON));
        HttpContext.Current.Response.End();
    }
}