Home > MVC > Different ways of Parameter can pass in Controller

Different ways of Parameter can pass in Controller

When you submit the data to action method of controller it can be done through the parameter. There are 4 different ways of parameter you can pass

1) Request object
2) FormCollection
3) using predefined datatypes
4) Custom datatype

When ever request object submit the data([HttpPost]) it will check with the action method’s parameter type based on that it will pass the parameter

1) Form Collection

It holds the value as key/value pair
While send the data back to the controller(Request object) we can send as FormCollection object.
If you specify as FormCollection type in action method signature you will get the user submitted value as key/value pair
Key contains control name and value will hold the value of the control.

Example:-
[HttpPost]
public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
{
foreach (string _formData in formCollection)
{

}

return View();
}

2) Request Object

It holds the values as Name-Value pairs.
While send the data back to the controller(Request object) we can submit the form as Post method.
If you are not specify action method signature and using Request[“ControlName”] you can get the value.

Example:
[HttpPost]
public ActionResult SubmitFormWithRequestObject(FormCollection formCollection)
{
int i=convert.ToInt32(Request[“txtAge”].toString())

return View();
}

3) Predefined parameter

Name of the control in View must be the variable name of parameter with data type.
We can define the parameter with the corresponding data type (int, string,…) that control will get as input.
For each control we will pass the separate parameter in the action method.

Example:
[HttpPost]
public ActionResult SubmitFormWithSimpleParameter(string txtName, string txtAddress, int txtAge, date txtDOB)
{
// Do some codes;

return View();
}

4) Custom Parameter

Custom data type can be passed as parameter
In the action method we passed model as parameter

Example:
[HttpPost]
public ActionResult SubmitFormWithSimpleParameter(PersonalInfo info)
{
// Do some codes;

return View();
}

Advertisements
Categories: MVC Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: