should formcollection be empty on asp.net mvc GET request
Asked Answered
U

1

10

i am posting a simple action.

public void Login(FormCollection formCollection)
{
   ...
}

Even with few querystring values, the formcollection.Count is 0. Is it by behaviour?

Uvular answered 15/2, 2010 at 10:15 Comment(2)
If your action is truly "simple", why don't you just declare action arguments for each variable you expect to be passed in? The MVC framework will automatically bind those variables for you which means that (1) it will work regardless of whether the variable is passed in the route, the URL, or the form data, and (2) it makes your code much easier to read, understand, and test. In most cases passing "FormCollection" to an argument is an anti-pattern and should be avoided.Indican
@Seth - What if the method is an ajax request handler? In that case, I'd rather return a proper Json(new{success=false,errorMsg="..."}) rather than the ASP.NET error page if the parameter is malformed or missing.Overburdensome
M
13

FormCollection uses POST values and not what's in the query string. Your action should look:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(FormCollection formCollection)
{
   ...
}
Manvell answered 15/2, 2010 at 10:17 Comment(4)
Thanks. I am trying to avoid Request object.Uvular
how would this be done using http get? I want to keep the values in the url to allow a user to save the results of a searchOrnithischian
@Chev, you use Request["paramName"] with GET requests.Manvell
@Chev: I realize purists would say you're doing something wrong if you're using the form collection in a get (or maybe if you're using it at all), but I simply don't agree; I'm using a get because I'm getting a FileResult, I'm not binding to my model object (for various reasons), and I can't separate my form fields into params because it includes a multi-select list. Thus, I'm just loading the collection myself: var realCollection = new FormCollection( Request.QueryString );Holtz

© 2022 - 2024 — McMap. All rights reserved.