63

I am new to C#.net MVC and am trying to add FullCalendar to an MVC application.

The FullCalendar script automatically adds ?start={}&end={} to the URL...which is fine, but I have no idea how to use querystring variables in a controller.

The methods I used in Webforms applications don't work. What do I need to add to the controller to access the querystring variables?

tereško
  • 58,060
  • 25
  • 98
  • 150
davids
  • 5,397
  • 12
  • 57
  • 94

6 Answers6

94
public ActionResult SomeAction(string start, string end)

The framework will map the query string parameters to the method parameters.

Maess
  • 4,118
  • 20
  • 29
  • 2
    I had tried that already, but the parameters were never assigned. I don't know if it matters that the querystring parameters were unixtimestamps, but neither double nor sting had any values when I tried this approach. – davids Jul 15 '12 at 01:55
  • 2
    This method worked for me. Important to note that the variable names have to match exactly. – Eric K Oct 27 '13 at 15:58
  • 1
    If you have default value for the param in route config, this default value will overwrite the query string value. – Tomas Kubes Jan 10 '16 at 08:05
  • 1
    In MVC terms, this is the only right way to do it. If it doesn't works for you, make sure that variable names match exactly your query parameter name. If it still doesn't works for you, go to your RouteConfig.cs and review your routes - probably something there configured incorrectly. – Illidan May 31 '17 at 06:45
  • Found my answer, yes it will – nuander Mar 11 '19 at 16:48
77

I figured it out...finally found another article on it.

string start = Request.QueryString["start"];

string end = Request.QueryString["end"];
Community
  • 1
  • 1
davids
  • 5,397
  • 12
  • 57
  • 94
  • 27
    Just saying this is wrong in terms of how it should be done within MVC. Check Maess' answer for the right one. – Dan Jul 21 '14 at 16:22
  • 1
    Yes. If you take this approach, you aren't understanding what makes MVC MVC. – jnm2 Dec 28 '14 at 00:10
  • 10
    This is like trying to figure out how to solve a Rubics cube, then in the end, you just peel the stickers off and put them back on in the solved position. – Christine Apr 27 '15 at 17:46
  • 20
    It's more like calling a Rubik's cube a Rubics cube. It's probably not the preferred method nor the method that was most commonly learned, but it achieved the outcome and now were off to solving bigger and better problems. Anyway, I used it to retrieve a URLEncoded url redirect path that was generating errors when embedded in the url. I'm not sure if that is the preferred way, but I am also guilty of peeling the stickers off a Rubix cube at some point in my life. Moving on.... – wavedrop May 20 '15 at 22:46
  • 11
    It is quite possible that you might want to do this in a controller and NOT be missing the point of MVC. – Don Rolling Sep 01 '15 at 18:55
  • 2
    Yes, I have a case where I want the query string key to be variable (user may do "?max=true" or "?maximum=true") in this case the standard MVC variable name in the controller method doesn't seem to help me at all as I can only choose one. This answer seems to be a solution for this use case – PandaWood Feb 03 '17 at 01:11
  • It is funny, but using Request["somevalue"] is the OLD 1999 way we used to catch query strings in old ASP VBScript. lol. What is old is new again! My question to Microsoft would be: Why did they waste 20 years on new tech to have us now go back to that old model??? – Stokely Aug 24 '17 at 22:45
  • I just wanted to quickly find out the syntax for any purpose, and this post helped confirm my thoughts already on the syntax. – Vasily Hall Nov 21 '17 at 16:38
  • If you want a `RouteValueDictionary` for the countless methods that consume one: [NameValueCollection.ToRouteValueDictionary() extension method](https://pastebin.com/embed_iframe/dC7AmKw8) – Sinjai Oct 12 '18 at 14:20
4

Davids, I had the exact same problem as you. MVC is not intuitive and it seems when they designed it the kiddos didn't understand the purpose or importance of an intuitive querystring system for MVC.

Querystrings are not set in the routes at all (RouteConfig). They are add-on "extra" parameters to Actions in the Controller. This is very confusing as the Action parameters are designed to process BOTH paths AND Querystrings. If you added parameters and they did not work, add a second one for the querystring as so:

This would be your action in your Controller class that catches the ID (which is actually just a path set in your RouteConfig file as a typical default path in MVC):

public ActionResult Hello(int id)

But to catch querystrings an additional parameter in your Controller needs to be the added (which is NOT set in your RouteConfig file, by the way):

public ActionResult Hello(int id, string start, string end)

This now listens for "/Hello?start=&end=" or "/Hello/?start=&end=" or "/Hello/45?start=&end=" assuming the "id" is set to optional in the RouteConfig.cs file.

If you wanted to create a "custom route" in the RouteConfig file that has no "id" path, you could leave off the "id" or other parameter after the action in that file. In that case your parameters in your Action method in the controller would process just querystrings.

I found this extremely confusing myself so you are not alone! They should have designed a simple way to add querystring routes for both specific named strings, any querystring name, and any number of querystrings in the RouteConfig file configuration design. By not doing that it leaves the whole use of querystrings in MVC web applications as questionable, which is pretty bizarre since querystrings have been a stable part of the World Wide Web since the mid-1990's. :(

Stokely
  • 12,444
  • 2
  • 35
  • 23
1

Here is what I came up with. I was having major problems with this and believe I am in MVC 6 now but this may be helpful to someone even myself in the future..

//The issue was that Reqest.Form Request.Querystring and Request not working in MVC the solution is to use Context.Request.Form and also making sure the form has been submitted otherwise null reference or context issue bug will show up.

     if(Context.Request.ContentLength != null)
     {
         String StartDate = Context.Request.Form["StartMonth"].ToString();
         String EndMonth = Context.Request.Form["EndMonth"].ToString();
        // Vendor

     }
Deathstalker
  • 794
  • 10
  • 8
1

My problem was overwriting my query string parameters with default values:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = ""}
);

No matter what I plugged into query string or how only key="" results.

Then got rid of default overwrites using UrlParameter.Optional:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);

now

prices/{key} 

or

prices?key={key} 

both work fine.

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
spugna
  • 11
  • 1
0

I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);

I followed this thread How to get Request Querystring values?

EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.

Hopefully this will help someone with the same problem..

Rawmouse
  • 77
  • 8