[c#] Use querystring variables in MVC controller

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?

This question is related to c# asp.net-mvc query-string

The answer is


public ActionResult SomeAction(string start, string end)

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


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.


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. :(


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

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

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

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

     }

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..


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to query-string

How can I get (query string) parameters from the URL in Next.js? How to read values from the querystring with ASP.NET Core? What is the difference between URL parameters and query strings? How to get URL parameter using jQuery or plain JavaScript? How to access the GET parameters after "?" in Express? node.js http 'get' request with query string parameters Escaping ampersand in URL In Go's http package, how do I get the query string on a POST request? Append values to query string Node.js: Difference between req.query[] and req.params