[SalesForce] Passing a value from Visualforce Page to Controller

How to pass a value from VF page to Apex Controller?
I need to have a hidden field with pre-populated value inside VF page.
Apex Controller must be able to read this value.
How to do that?

EDIT:

By saying "a hidden field", I did not mean the actual field on the Salesforce object but instead just some kind of value holder which could be accessed and read from the Controller. That value will be hard-coded in the VF page.

Best Answer

The easiest way I've found to do this is using window.setTimeout() with an abitrary low delay value which calls an apex:actionFunction that rerenders a dummy apex:outputPanel within an apex:actionRegion.

<script>
    window.setTimeout(function() { setParams("param1Value", "param2Value"); }, 1);
</script>

<apex:actionRegion>
    <apex:actionFunction action="{!setParams}" name="setParams" rerender="dummy">
        <apex:param name="param1" assignTo="{!param1}" value="" />
        <apex:param name="param2" assignTo="{!param2}" value="" />
    </apex:actionFunction>
    <apex:outputPanel id="dummy"/>
</apex:actionRegion>

The apex:actionRegion and the dummy apex:outputPanel prevent the whole page refreshing when the apex:actionFunction is called which will result in your JavaScript being called everytime and ending up in a refresh loop.

The apex:actionRegion also prevents the following error occurring when this is used on a page with an apex:inputFile component.

apex:inputFile can not be used in conjunction with an action component, apex:commandButton or apex:commandLink that specifies a rerender or oncomplete attribute

Your controller will looks something like this:

public class ParameterPageController
{
    public String param1 { get; set; }
    public String param2 { get; set; }

    public PageReference setParams()
    {
        return null;
    }
}

Edit:
You don't actually need the window.setTimeout() call at all and can simply call your apex:actionFunction directly, however you must put your call to your apex:actionFunction after (although not necessarily directly after) it's declaration for this to work.

<apex:actionRegion>
    <apex:actionFunction ... >
        ...
    </apex:actionFunction>
    ..
</apex:actionRegion>

 |
 |
 |

<script>
    setParams("param1Value", "param2Value");
</script>