In our real world of application development, sometimes we need to create dynamic pages in our application. In this article, we will learn about creating the dynamic pages in asp.net mvc. It is suggested to read MVC Url rewriting , if you haven’t idea about MVC Url rewriting or MVC Url Routing.
Generating SEO based Url in ASP.net MVC
Let’s assume a scenario where we can use to generate dynamic pages. If we are developing any MVC application, in which we have multiple objects of a very same entity e.g. a product details page. We have multiple products. We also have multiple categories having different product. To handle this kind of situation we can create a common page for product details with a query string. But this will not suggested due to reason of, it’s not SEO (search engine optimization) . It is demand of our application to follow SEO rule.
To resolve this issue we should use category name in page with product name. See following example of Url, which will allow us to solve our problem.
Yourdomain.com/productdetail?pid=1
Yourdomain.com/product-detail/sample-product-detail
In 1st case we have a page in which we will use querystring to pass the id of the product. But in second url we doesn’t have any QueryString we have only product name. It looks very neat & clean as well as SEO friendly.
To achieve this in MVC. We will create a Controller and a corresponding Action & View. We will use MVC Url rewriting to map our url to related products. We will not use any database here but we will use a collection to store our sample data.
We will also append productid in sample Url witch allow us to get our productid at view, and can be used to show product details as par productId. Our new url will became like-
Yourdomain.com/product-detail /sample-product-detail-1
In this case we can use product name & product Id column in url.
Generating Dynamic Pages Step by Step
- Create a MVC Controller with ProductController name.
- Create a MVC Action in ProductController with name ProductDetail.
- Add a View for this Action with same name as Action.
- Define rule for our new Url in RouteTable with ProductId & ProductName as route parameter.
- Receive this parameter value at the MVC Action.
- Use this parameter value at our View.
Do watch following video to implement above mentions steps in ASP.net MVC.
Summary: In this article we have learn, how to create dynamic pages using ASP.Net MVC with MVC Routing & Url Rewriting. It is suggested to read MVC Url rewriting . We have a video tutorial for this article. I hope you will like this article and find it useful.