0

Good Morning. Came across code implemented by someone else and I'm not understanding how the FormCollection is used. Is the FormCollection merely a collection of the controls on the form?

        public Email(FormCollection fc)
        {
            StringBuilder sb = new StringBuilder();
            this.fc = fc;
            string[] keys = fc.AllKeys;

            sb.Append("Category,\"REQUEST\",<br />");
            sb.Append("Type,\"TEST EXPRS\",<br />");
         }
tereško
  • 58,060
  • 25
  • 98
  • 150
Susan
  • 1,822
  • 8
  • 47
  • 69
  • this has been posted earlier you can check this [link](http://stackoverflow.com/questions/762825/how-can-a-formcollection-be-enumerated-in-asp-net-mvc) for an example how to use FormCollection – SShebly Oct 31 '11 at 13:49

2 Answers2

5

In this particular code snippet it is not used and completely unnecessary as argument.

Personally I never use FormCollection in ASP.NET MVC applications. I always prefer to define a view model and have the controller action take this view model as argument. Its properties will be automatically populated by the default model binder. For example:

public class MyViewModel
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
    ...
}

and then:

public Email(MyViewModel model)
{
    // use the view model here
    ...
}

But back to your question: FormCollection represents a key value pair of all POSTed values. It is weakly typed and the values are always string meaning that you will have to manually convert them to their underlying type if you wanted to manipulate them. Try to avoid it.

Murph
  • 9,985
  • 2
  • 26
  • 41
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    @Murph, I just shared what I consider as good practice. And having controller actions that take FormCollection as parameter is IMHO not a good practice. That's all. Of course everyone has his own definition of good practice and I appreciate your input. – Darin Dimitrov Oct 31 '11 at 13:52
  • Ok, the answer I commented on was not the answer above... so I've removed the downvote – Murph Oct 31 '11 at 16:01
0

The code is a little odd as they are committing the keys to a string array rather than looping through it. The original code probably looked something like this:

FormCollection fc;

public Email(FormCollection fc)
    {
        StringBuilder sb = new StringBuilder();
        this.fc = fc;
        string[] keys = fc.AllKeys;

        sb.Append("Category," + fc[keys[0]] + ",<br />");
        sb.Append("Type,"+ fc[keys[1]] +",<br />");
     }

I think that would work and is possibly how they were getting the values out. It's certainly not the best way.

As Darin pointed out the formhandler does not even appear to be used for anything, so at some point maybe whoever wrote this was expecting there to be multiple categories and types and then just hardcoded some options.

boolean
  • 891
  • 2
  • 14
  • 23