1

I am a .NET newbie. I am using Visual Studio 2017. I get a red squiggly line when i enter this code

    string firstname = Request.QueryString["firstname"]

I am actually trying to get information from a form using context objects. I have also added a screenshot to show what error I am actually getting.enter image description here

Amruth Lakkavaram
  • 1,467
  • 1
  • 9
  • 12

2 Answers2

3

the QueryString is not a dictionary-like type from which you can access its members with the brackets notation.

This property is used to see the raw queryString, but offers no direct facility to access individual components.


To actually get extract the parameters from your queryString, you can have a look at this question and its answers : Get url parameters from a string in .NET

(basically, you could use : HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("firstname") )


However, for a proper ASP.NET MVC way of getting the parameters from the query, see Hans Kesting's answer

Pac0
  • 21,465
  • 8
  • 65
  • 74
  • The code snippet you mentioned doesn't seem to be working. It says QueryString cannot be converted to a string.So I guess this snippet is the right one.

    HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("firstname") ) is working.
    – Amruth Lakkavaram Dec 29 '17 at 14:01
  • Yes you are right, QueryString is not of type `string`, it is indeed QueryString.ToString() that you have to use. I fixed my answer. Anyway, you *can* use such methods to access parameters, but the good practice is to use parameters of the Action as the other answer tells. – Pac0 Dec 29 '17 at 14:13
2

You are apparently using MVC. Then you usually don't need to access Request directly. Instead use this method signature:

public ActionResult MySubmitAction(string firstname, string lastname)

The arguments will be filled automatically.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • yes ! This **is** (one of) the proper ways of using ASP.NET MVC – Pac0 Dec 29 '17 at 13:37
  • 1
    to avoid any surprise later, you can also annotate the parameters with `[FromQuery]`, to ensure these actually come from the query string (and not the body or the route, for instance) : `MySubmitAction([FromQuery] string firstname, [FromQuery] string lastname)` – Pac0 Dec 29 '17 at 13:40