How to get url desire value in asp.net C#

http://example.com/UI/ProductUI.aspx/GetProductByCategory/1

Regarding the url, I want to pass the url value 1 in my content page method parameter when click in left navigation. The left navigation item is my Category Item and I load it from my category table in my master page by looping. Now I need the item value field e.g categoryId pass my content page method perimeter when click this item.

My Master page code is below:

    <div class="left">
                        <%
                            CategoryManager aCategoryManager=new CategoryManager();
                            List<Category> categories = aCategoryManager.GetCategories();

                            foreach (Category  category in categories)
                            {%>
                            <ul>
                                <li><a href="/UI/ProductUI.aspx/GetProductByCategory/<%: category.CategoryId %>"><%: category.CategoryName%></a></li>

                            </ul>

                            <% }%>
                    </div>

and my content page code is below:

protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {

                int id = Convert.ToInt32(Request.QueryString["CategoryId"]);
                GetProductByCategory(id);                

            }


        }
        ProductManager aProductManager=new ProductManager();

        private void GetProductByCategory(int categoryId)
        {
            List<Product> products = aProductManager.GetProductByCategory(categoryId);
            GridView1.DataSource = products;
            GridView1.DataBind();
        } 

Upvotes: 0

Views: 255

Answers (1)

iamchrisfryer
iamchrisfryer

Reputation: 290

In the method GetProductByCategory rename the parameter to int id

    private void GetProductByCategory(int id)
    {
        List<Product> products = aProductManager.GetProductByCategory(id);
        GridView1.DataSource = products;
        GridView1.DataBind();
    } 

This would allow you to keep the <li><a href="/UI/ProductUI.aspx/GetProductByCategory/<%: category.CategoryId %>"><%: category.CategoryName%></a></li> code as is and it should pick up the passed in CategoryId as the id

In the default routes it's looking for an id parameter.

    routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

Otherwise @karl-anderson answer should work for you.

Upvotes: 1

Related Questions