× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to make a dynamic page in ASP .NET C# using query strings to pass information

Rory O'Keeffe
Nov 17, 2016
<p>You have your app and all the static pages are working well. The thing is, for this to really be an app, you need to have something dynamic happening.</p> <p>Let's say for example that you have an eCommerce app, and you need a Product.aspx page that will look right for all your different products. You create a <code>Product.aspx</code> page and then want to link your products to it.</p> <p>The link from the product looks like this:</p> <pre><code class="language-html">&lt;a href="Product.aspx"&gt;Link to my awesome product!&lt;/a&gt;</code></pre> <p>But hold on, when you click that you just get the same product page for every product. How do we make it dynamic?</p> <p>By using a nice query string to tell the <code>Product.aspx</code> page which product it needs to display!</p> <p>In Product.aspx, you'd have something like this:</p> <pre><code class="language-cs">// using statements and page definition // On page load... protected void Page_Load(object sender, EventArgs e) { // ... if it's not after a postback... if (!Page.IsPostBack) { string productId = ""; // ...get the productId from a query string "productId". if(Request.QueryString.AllKeys.Contains("productId")) { productId = Request.QueryString.Get("productId"; } // Check that is has a length greater than 0 (i.e. there is an id) if (productId.Length &gt; 0) { // if we have a productId, populate the page! PopulateProductPage(productId); } else { // otherwise redirect them back to all products Response.Redirect("products.aspx"); } } }</code></pre> <p><img><img style="height:15px; width:15px"></p> <p>And your product link becomes:</p> <pre><code class="language-html">&lt;a href="Product.aspx?productId=1"&gt;Link to my awesome product!&lt;/a&gt;</code></pre> <p>See that <code>?productId=1</code> piece in the new link? Anything after a <code>?</code> in a URL is a query string (and to add more than one query string you append them with a &amp;, e.g. <code>url.com?foo=1&amp;bar=2</code>).</p> <p>With this query string in place, your page can now load all the information for the product with the passed-in query string productId and populate the page with it (all part of your new <code>PopulateProductPage()</code> method).</p> <p>Hope that helps!</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus