locked
find by name in web api RRS feed

  • Question

  • User81789783 posted

    i followed below link and its working fine its searching  by id

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

    now i want to search by name but unable to do so . i write below code but not working

        public IHttpActionResult GetAllProduct(string name)
            {
                var product = products.FirstOrDefault((p) => p.Name == name);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
     function findByName() {
          
            var name = $('#prodName').val();
            alert(id)
            $.getJSON(uri + '/' + name)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }

    Saturday, December 12, 2020 2:51 PM

Answers

  • User475983607 posted

    You did not answer any of the questions which indicates a lack of troubleshooting or not following the official documentation.  It's hard to tell without your feedback.

    Since you still have not provided all the relevant code, I'm guessing the error is due to calling the same action but passing two different route types; int and string.

    var uri = 'api/products';
        function findByName() {
          
            var name = $('#prodName').val();
            alert(id)
            $.getJSON(uri + '/' + name)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }
    
        function find() {
            var id = $('#prodId').val();
            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }

    I recommend implementing attribute routing and using constraints to select the action.  See the following example.

    WebApiConfig.cs

            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace ApiBasic.Controllers
    {  
        public class ProductController : ApiController
        {
            Product[] products = new Product[]
           {
                new Product { Id = 1, Name = "a", Category = "Groceries", Price = 1 },
                new Product { Id = 2, Name = "b", Category = "Toys", Price = 3.75m},
                new Product { Id = 3, Name = "c", Category = "Hardware", Price = 16.99m }
           };
    
            //Get: api/product
            [Route("api/product")]
            public IEnumerable<Product> GetAllProducts()
            {
                return products;
            }
    
            //Get: api/product/1
            [Route("api/product/{id:int}")]
            public IHttpActionResult GetProductById(int id)
            {
                var product = products.FirstOrDefault((p) => p.Id == id);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
    
            //Get: api/product/b
            [Route("api/product/{name}")]
            public IHttpActionResult GetProductByName(string name)
            {
                var product = products.FirstOrDefault(p => p.Name == name);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
        }
    }   
    

    Example URLs

    https://localhost:44310/api/product
    https://localhost:44310/api/product/1
    https://localhost:44310/api/product/b

    I also recommend setting aside time to learn Web API and Web API routing basics.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2




     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, December 13, 2020 3:01 PM

All replies

  • User475983607 posted

    You did not provide the relevant code or describe what "not working" means.  I recommend rudimentary troubleshooting.  Run the code through the debugger and answering the following questions.

    What is the value of uri?  What is the value of name?  What does formatItem() do?   Can you share the code for formatItem()?  Share the results from the getAllProduct() action.  Does the action return a 404?  Does the action return JSON?   

    Saturday, December 12, 2020 4:03 PM
  • User81789783 posted

    in action method its saying bad request in browser console

    Sunday, December 13, 2020 5:50 AM
  • User81789783 posted

    here is full code

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Product App</title>
    </head>
    <body>
    
        <div>
            <h2>All Products</h2>
            <ul id="products" />
        </div>
        <div>
            <h2>All Products</h2>
            <ul id="products2" />
        </div>
        <div>
            <h2>Add Products</h2>
            <input type="button" value="Add Products" onclick="AddProducts();" />
        </div>
        <div>
            <h2>Search by ID</h2>
            <input type="text" id="prodId" size="5" />
            <input type="button" value="Search" onclick="find();" />
            <p id="product" />
        </div>
        <div>
            <h2>Search by Name</h2>
            <input type="text" id="prodName" size="15" />
            <input type="button" value="Search by name" onclick="findByName();" />
            <!--<p id="productName" />-->
        </div>
        <div>
            <h2>Search allll</h2>
            <!--<input type="text" id="prodId" size="5" />-->
            <input type="button" value="Search" onclick="find2();" />
            <p id="product" />
        </div>
    
        <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
        <script>
        var uri = 'api/products';
    
        $(document).ready(function () {
            // Send an AJAX request
            alert();
            $.getJSON(uri)
        
              .done(function (data) {
                // On success, 'data' contains a list of products.
                $.each(data, function (key, item) {
                  // Add a list item for the product.
                  $('<li>', { text: formatItem(item) }).appendTo($('#products'));
                });
              });
        });
    
        function formatItem(item) {
          return item.Name + ': $' + item.Price;
        }
        
        function findByName() {
          
            var name = $('#prodName').val();
            alert(id)
            $.getJSON(uri + '/' + name)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }
    
        function find() {
            var id = $('#prodId').val();
            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }
    
        function AddProducts() {
            //uri = 
    
            product
            $.getJSON(uri + '/' + product)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }
    
        function find2() {
          
            $.getJSON(uri)
               .done(function (data) {
                   // On success, 'data' contains a list of products.
                   $.each(data, function (key, item) {
                       // Add a list item for the product.
                       $('<li>', { text: formatItem(item) }).appendTo($('#products2'));
                   });
               });
        }
        </script>
    </body>
    </html>
    

    Sunday, December 13, 2020 5:54 AM
  • User475983607 posted

    You did not answer any of the questions which indicates a lack of troubleshooting or not following the official documentation.  It's hard to tell without your feedback.

    Since you still have not provided all the relevant code, I'm guessing the error is due to calling the same action but passing two different route types; int and string.

    var uri = 'api/products';
        function findByName() {
          
            var name = $('#prodName').val();
            alert(id)
            $.getJSON(uri + '/' + name)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }
    
        function find() {
            var id = $('#prodId').val();
            $.getJSON(uri + '/' + id)
                .done(function (data) {
                    $('#product').text(formatItem(data));
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#product').text('Error: ' + err);
                });
        }

    I recommend implementing attribute routing and using constraints to select the action.  See the following example.

    WebApiConfig.cs

            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    namespace ApiBasic.Controllers
    {  
        public class ProductController : ApiController
        {
            Product[] products = new Product[]
           {
                new Product { Id = 1, Name = "a", Category = "Groceries", Price = 1 },
                new Product { Id = 2, Name = "b", Category = "Toys", Price = 3.75m},
                new Product { Id = 3, Name = "c", Category = "Hardware", Price = 16.99m }
           };
    
            //Get: api/product
            [Route("api/product")]
            public IEnumerable<Product> GetAllProducts()
            {
                return products;
            }
    
            //Get: api/product/1
            [Route("api/product/{id:int}")]
            public IHttpActionResult GetProductById(int id)
            {
                var product = products.FirstOrDefault((p) => p.Id == id);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
    
            //Get: api/product/b
            [Route("api/product/{name}")]
            public IHttpActionResult GetProductByName(string name)
            {
                var product = products.FirstOrDefault(p => p.Name == name);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
        }
    }   
    

    Example URLs

    https://localhost:44310/api/product
    https://localhost:44310/api/product/1
    https://localhost:44310/api/product/b

    I also recommend setting aside time to learn Web API and Web API routing basics.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2




     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, December 13, 2020 3:01 PM
  • User81789783 posted

    solved thanks

    Monday, December 14, 2020 5:45 AM