MyDaftQuestions
MyDaftQuestions

Reputation: 4691

How to get querystring value after MVC routing

I'm guessing my approach is wrong, which is why my research produced little results

My website was using querystrings, and within my HtmlHelper class I could get the query string with the following code

When you start MVC4, the defulat route lets you pass an ID as a querystring. The routing engine 'converts' this from a querystring into part of the URL How do I then query this value?

public static MvcHtmlString ActionLinkWithQueryString(this HtmlHelper helper, string linkText, string action, string controllerName, object routeValues)
{
    var queryString = helper.ViewContext.HttpContext.Request.QueryString;
    ... 

The above works fine.

However, I'm now using the routing engine. When you first start with MVC, you get the ID parameter set up for you, and when you perform a search similar to www.mysite.com/?id=HelloWorld the routing engine 'converts' or 'translates' this into a URL , such as www.mysite.com/HelloWorld

The issue is, I still need to get that value - the HelloWorld value.

Using the code above always returns an empty list because there is no querystring!

I know I can just read the URL, split by forward slash and then get the item out of the array but, I'm hoping there is a more elegant way.

The real reason for this is due to pagination. What is happening is my URL is www.mysite.com/products/shoes/12

I then click on next page and it loses the values, showing me www.mysite.com/products/10 (where 10 is the starting index). Obviously I need the URL to be www.mysite.com/products/10/shoes/12

How do I get the value HelloWorld (ID parameter) from the URL?

Upvotes: 0

Views: 1259

Answers (1)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You can get it from route values:

object id = helper.ViewContext.RouteData.Values["id"];

Upvotes: 1

Related Questions