【问题标题】:Populating data to GridView using Ajax, Post Method is not working. How to solve this?使用 Ajax 将数据填充到 GridView,Post 方法不起作用。如何解决这个问题?
【发布时间】:2017-08-04 07:36:12
【问题描述】:

我刚刚创建了一个 ASP.Net Web 应用程序,其中包含参考“WEB API”的空模板。在其中,我创建了一个名为“ProductsWebForm.aspx”的 Web 表单和一个名为“ProductsWebAPIEmptyController.cs”的控制器。 Gridview 中未填充数据,它会警告“未定义”。在控制台内,错误消息是:

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:55119/api/ProductsWebAPIEmptyController'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'ProductsWebAPIEmptyController'.
</MessageDetail>
</Error>

这是我在 WEBForm "ProductsWebForm.aspx" 中的代码:

<body>
    <form id="form1" runat="server">
    <div>

    </div>
       <asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False">
            <Columns>
                         <asp:TemplateField HeaderText="Product_Id" ItemStyle-Width="110px" ItemStyle-CssClass="Product_Id">
            <ItemTemplate>
                <asp:Label Text='<%# Eval("Product_Id") %>' runat="server" />
            </ItemTemplate>

<ItemStyle CssClass="Product_Id" Width="110px"></ItemStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Product_Name" ItemStyle-Width="150px" ItemStyle-CssClass="Product_Name">
            <ItemTemplate>
                <asp:Label Text='<%# Eval("Product_Name") %>' runat="server" />
                <asp:TextBox Text='<%# Eval("Product_Name") %>' runat="server" Style="display: none" />
            </ItemTemplate>

<ItemStyle CssClass="Product_Name" Width="150px"></ItemStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Product_Description" ItemStyle-Width="150px" ItemStyle-CssClass="Product_Description">
            <ItemTemplate>
                <asp:Label Text='<%# Eval("Product_Description") %>' runat="server" />
                <asp:TextBox Text='<%# Eval("Product_Description") %>' runat="server" Style="display: none" />
            </ItemTemplate>

<ItemStyle CssClass="Product_Description" Width="150px"></ItemStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Product_Category" ItemStyle-Width="150px" ItemStyle-CssClass="Product_Category">
            <ItemTemplate>
                <asp:Label Text='<%# Eval("Product_Category") %>' runat="server" />
                <asp:DropDownList ID="DropDownList1" runat="server" >
                            <asp:ListItem>Select Category</asp:ListItem>
                            <asp:ListItem>Laptops</asp:ListItem>
                            <asp:ListItem>Mobiles</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>

<ItemStyle CssClass="Product_Category" Width="150px"></ItemStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Product_Price" ItemStyle-Width="150px" ItemStyle-CssClass="Product_Price">
            <ItemTemplate>
                <asp:Label Text='<%# Eval("Product_Price") %>' runat="server" />
                <asp:TextBox Text='<%# Eval("Product_Price") %>' runat="server" Style="display: none" />
            </ItemTemplate>

<ItemStyle CssClass="Product_Price" Width="150px"></ItemStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Prodcut_Quantity" ItemStyle-Width="150px" ItemStyle-CssClass="Product_Quantity">
            <ItemTemplate>
                <asp:Label Text='<%# Eval("Product_Quantity") %>' runat="server" />
                <asp:TextBox Text='<%# Eval("Product_Quantity") %>' runat="server" Style="display: none" />
            </ItemTemplate>

<ItemStyle CssClass="Product_Quantity" Width="150px"></ItemStyle>
        </asp:TemplateField>
           <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton Text="Edit" runat="server" CssClass="Edit" />
                <asp:LinkButton Text="Update" runat="server" CssClass="Update" Style="display: none" />
                <asp:LinkButton Text="Cancel" runat="server" CssClass="Cancel" Style="display: none" />
                <asp:LinkButton Text="Delete" runat="server" CssClass="Delete" />
            </ItemTemplate>
        </asp:TemplateField>

    </Columns>
</asp:GridView>
 <table border="1"  style="border-collapse: collapse">
      <tr>
         <td style="width: 150px">Product
                    Name:<br />
                <asp:TextBox ID="txtName" runat="server" Width="140" />
        </td>
        <td style="width: 150px">
                Product Description:<br />
            <asp:TextBox ID="txtDescription" runat="server" Width="140" />
        </td>
        <td style="width: 150px">
            Product Category:<br />
            <asp:DropDownList ID="InsertDropDownList" runat="server">
                            <asp:ListItem>Select Category</asp:ListItem>
                            <asp:ListItem>Laptops</asp:ListItem>
                            <asp:ListItem>Mobiles</asp:ListItem>


             </asp:DropDownList>
        </td>
        <td style="width: 150px">
            Product Price:<br />
            <asp:TextBox ID="txtPrice" runat="server" Width="140" />
        </td>
        <td style="width: 150px">
            Product Quantity:<br />
            <asp:TextBox ID="txtQuantity" runat="server" Width="140" />
        </td>
        <td style="width: 100px">
            <br />
            <asp:Button ID="btnAdd" runat="server" Text="Add" />
        </td>
    </tr>
</table>
    </form>

这是我的代码 ajax jquery 代码:

 <script type="text/javascript">
     $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "/api/ProductsWebAPIEmptyController",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function(response)
            {
                alert(response.d);

            },
            error: function(response)
        {
                alert(response.d);
        }
        });
    });

     function OnSuccess(response) {
         //console.log(response.d);
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        var products = xml.find("Table");
        var row = $("[id*=GridView1] tr:last-child").clone(true);
        $("[id*=GridView1] tr").not($("[id*=GridView1] tr:first-child")).remove();
        $.each(products, function () {
            var customer = $(this);
            AppendRow(row, $(this).find("Product_Id").text(), $(this).find("Product_Name").text(), $(this).find("Product_Description").text(), $(this).find("Product_Category").text(), $(this).find("Product_Price").text(), $(this).find("Product_Quantity").text())
            row = $("[id*=GridView1] tr:last-child").clone(true);
        });
    }
    function AppendRow(row, Product_Id, Product_Name, Product_Description, Product_Category, Product_Price, Product_Quantity) {
        //Bind ProductId.
        $(".Product_Id", row).find("span").html(Product_Id);

        //Bind Name.
        $(".Product_Name", row).find("span").html(Product_Name);
        $(".Product_Name", row).find("input").val(Product_Name);

        $("Product_Description", row).find("span").html(Product_Description);
        $("Product_Description", row).find("input").val(Product_Description);

        $("Product_Category", row).find("span").html(Product_Category);
        $("Product_Category", row).find("input").val(Product_Category);


        $("Product_Price", row).find("span").html(Product_Price);
        $("Product_Price", row).find("input").val(Product_Price);

        $("Product_Quantity", row).find("span").html(Product_Quantity);
        $("Product_Quantity", row).find("input").val(Product_Quantity);
        $("[id*=GridView1]").append(row);
    }

我什至尝试了 url:"/api/ProductsWebAPIEmptyController/GetProducts"。这是我在 ProductsWebForm.aspx.cs 中的代码:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.BindDummyRow();
            }
        }
        private void BindDummyRow()
        {
            DataTable dummy = new DataTable();
            dummy.Columns.Add("Product_Id");
            dummy.Columns.Add("Product_Name");
            dummy.Columns.Add("Product_Description");
            dummy.Columns.Add("Product_Category");
            dummy.Columns.Add("Product_Price");
            dummy.Columns.Add("Product_Quantity");
            dummy.Rows.Add();
            GridView1.DataSource = dummy;
            GridView1.DataBind();


        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

我创建了名为“ProductsWebAPIEmptyController.cs”的 WebAPI 2 Controller Empty:

namespace GridViewWithAjaxIIIWebApplication.Controllers
{   
    public class ProductsWebAPIEmptyController : ApiController
    {
        [WebMethod]
        public static string GetCustomers()
        {
            string query = "Select Product_Id, Product_Name, Product_Description, Product_Category, Product_Price, Product_Quantity from Items";


            String cs = ConfigurationManager.ConnectionStrings["WebShopDB"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    SqlCommand cmd = new SqlCommand();
                    sda.SelectCommand = cmd;
                    cmd.Connection = con;
                    cmd.CommandText = query;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        return ds.GetXml();
                    }
                }
            }
        }
    }
}

请帮我运行这段代码:enter image description here

【问题讨论】:

  • 阅读这个stackoverflow.com/questions/1552984/…和这个stackoverflow.com/questions/1144153/…最后这个stackoverflow.com/questions/3103360/…,将帮助你理解asp.net、asp.net MVC和ASP.net Web API。
  • 现在您知道了 IsPostBack 的用法,并将更新或删除您的问题。
  • 我读到了。我明白了。因为它为开发人员提供了高度的控制并支持测试驱动开发。阅读此博客后:weblogs.asp.net/shijuvarghese/asp-net-mvc-vs-asp-net-web-form。我有个问题。我在上面的 Web 应用程序中制作了一个控制器,还包含了 WEB API。我们只能在 MVC 甚至 Web 表单应用程序中制作控制器和应用 REST API?请帮我理解
  • 这取决于物理架构,如果api和form在同一台服务器上,那么您可以使用api作为DLL引用,不需要作为http请求调用。如果它在 diff 服务器上,那么您不能使用 dll,然后将其作为 http 请求调用,并带有合适的动词,如 GET/POST。
  • IsPostBack 用于通过 Post 请求向服务器发送数据。此处页面加载实现 (!IsPostBack) 以在页面加载时首次将数据绑定到 GridView。我必须使用 ViewState 来保存数据还是什么?我不认为错误是由于这个。ajax URL 中是否有任何错误?

标签: c# jquery asp.net ajax gridview


【解决方案1】:

App_Start/WebApiConfig2.cs 中的Adding Routing Information 将启用通过 http 的 api 访问。

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

与 HTTP Post 一起使用,添加属性

namespace GridViewWithAjaxIIIWebApplication.Controllers
{   
    public class ProductsWebAPIEmptyController : ApiController
    {
        [HttpGet, HttpPost ]
        public static string GetCustomers()
        {
            string query = "Select Product_Id, Product_Name, Product_Description, Product_Category, Product_Price, Product_Quantity from Items";


            String cs = ConfigurationManager.ConnectionStrings["WebShopDB"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    SqlCommand cmd = new SqlCommand();
                    sda.SelectCommand = cmd;
                    cmd.Connection = con;
                    cmd.CommandText = query;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        return ds.GetXml();
                    }
                }
            }
        }
    }
}

并在 URL 中使用动作名称

<script type="text/javascript">
     $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "/api/ProductsWebAPIEmptyController/GetCustomers",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function(response)
            {
                alert(response.d);

            },
            error: function(response)
        {
                alert(response.d);
        }
        });
    });

【讨论】:

  • 在文件 'WebApiConfig.cs' 我有 public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id} ",默认值:新 { id = RouteParameter.Optional } );在 Global.asax.cs 我有: protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register);我已经使用 CDN 加载 jquery 文件。我
  • [HttpGet,HttpPost] and url: "/api/ProductsWebAPIEmptyController/GetCustomers" 没用我什至试过这个 .webServer> 但同样的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多