-2

I just created an ASP.Net Web Application that includes empty templates with reference to 'WEB API'. Inside that I created a Web Form named "ProductsWebForm.aspx" and a controller named "ProductsWebAPIEmptyController.cs". Data is not populated in Gridview and it alerts "Undefined". Inside the console the error message was:

<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>

Here is my code inside 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>

Here is my code ajax jquery code:

 <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);
    }

I even tried url:"/api/ProductsWebAPIEmptyController/GetProducts". THis is my code inside 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)
        {

        }
    }
}

I created WebAPI 2 Controller Empty named "ProductsWebAPIEmptyController.cs" :

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();
                    }
                }
            }
        }
    }
}

Please help me to run this code:enter image description here

Utshab Khadka
  • 121
  • 1
  • 9
  • reading this http://stackoverflow.com/questions/1552984/asp-net-mvc-vs-asp-net-forms and this http://stackoverflow.com/questions/1144153/when-to-use-asp-net-mvc-vs-asp-net-web-forms and finally this http://stackoverflow.com/questions/3103360/net-vs-asp-net-vs-clr-vs-asp, will help you to understand asp.net, asp.net MVC and ASP.net Web API. – Anil Mar 14 '17 at 05:00
  • So now you know the use of IsPostBack and will update or delete your question. – Anil Mar 14 '17 at 05:44
  • I read that. I got the difference. As it provides high degree of control to the developers and supports Test Driven Development.After reading this blog : https://weblogs.asp.net/shijuvarghese/asp-net-mvc-vs-asp-net-web-form. I have a question. I made a controller in the above Web application and also included WEB API. We can make controller and apply REST API only in MVC or even in Web Form Application? Please help me to understand – Utshab Khadka Mar 14 '17 at 05:50
  • It depends on the physical architecture, if api and form is on same server then you can use api as DLL reference, do not need to call as http request. If its on diff server then you can not use dll then will call it as http request with suitable verb like GET/POST. – Anil Mar 14 '17 at 06:06
  • IsPostBack is used to send data to server via Post request.Here page load implements (!IsPostBack ) to bind the data to the GridView for the first time when page loads.I have to use ViewState to preserve the data or what ? I don't think that the error is due to this.Is there any error in ajax URL ? – Utshab Khadka Mar 15 '17 at 05:48
  • have you created App_Start/WebApiConfig2.cs and registered the routes, you should follow the approach https://dzone.com/articles/web-api-aspnet-web-forms and http://stackoverflow.com/questions/20538119/adding-web-api-to-existing-asp-net-web-forms-application and msdn link https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/using-web-api-with-aspnet-web-forms – Anil Mar 15 '17 at 06:00
  • URL should be in this format url: "PageName.aspx/MethodName" and in my case it would be url:"ProductsWebAPIEmptyController.cs/GetProducts".Because my method is inside controller not inside .aspx page.I got this from http://stackoverflow.com/questions/5331986/how-to-use-ajax-with-asp-net-webforms.And I will create and register the routes – Utshab Khadka Mar 15 '17 at 06:07

1 Answers1

0

Adding Routing Information in App_Start/WebApiConfig2.cs will enable api access over http.

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

For use with HTTP Post, add attribute

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();
                    }
                }
            }
        }
    }
}

and use the action name in 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);
        }
        });
    });
Anil
  • 3,722
  • 2
  • 24
  • 49
  • Inside file 'WebApiConfig.cs' I have public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } Inside Global.asax.cs I have: protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } I have used CDN to load jquery file.I – Utshab Khadka Mar 15 '17 at 07:02
  • [HttpGet,HttpPost] and url: "/api/ProductsWebAPIEmptyController/GetCustomers" Did not worked I even tried this But the same error – Utshab Khadka Mar 15 '17 at 09:36