Pass Data from View to Controller in ASP.NET - Part 1

There are basically four different methods:

  1. Using Request Object.
  2. Using Formcollection Class Object.
  3. Using Parameters.
  4. Using Model Class Object.

Here, we will discuss the first two methods.

Using Request Object.

Here, we will use Name-Value pair technique.

Name Value
EmployeeName Mayank Sharma
EmployeeNumber 123456789
EmployeeAddress Mumbai, India

We have three pieces of data in Name-Value pairs. So we can access these data in a POST method by passing the Name as an indexer in the Request and getting the values.

Create an action method in the HomeController (Home.cs) that renders the view on the UI.

  1. [HttpGet]  
  2. public ActionResult EmployeeResult()  
  3. {  
  4.     return View();  
  5. }  
  6. [HttpPost]  
  7. public ActionResult EmployeeResult()  
  8. {  
  9.     string name = Request["EmployeeName"].ToString();  
  10.     string number = Request["EmployeeNumber"].ToString();  
  11.     string address = Request["EmployeeAddress"].ToString();  
  12.     StringBuilder strs = new StringBuilder();  
  13.     strs.Append("<b>Name:</b> " + name + "<br/>");  
  14.     strs.Append("<b>Number:</b> " + number + "<br/>");  
  15.     strs.Append("<b>Address :</b> " + address + "<br/>");  
  16. }  
View
  1. <fieldset>  
  2.     <legend>Employee Result</legend>  
  3.     @using (Ajax.BeginForm("EmployeeResult","Home"new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divResult" })) {  
  4.     <div id="divResult">  
  5.     </div>  
  6.     <ol>  
  7.         <li> @Html.Label("Name") @Html.TextBox("EmployeeName")  
  8.         </li>  
  9.         <li> @Html.Label("Number") @Html.TextBox("EmployeeNumber")  
  10.         </li>  
  11.         <li> @Html.Label("Address") @Html.TextBox("EmployeeAddress")  
  12.         </li>  
  13.     </ol>  
  14.     <button>Submit</button> }  
  15. </fieldset>  
Here is the Output.
 

Name

Mayank Sharma
Number
123456789
Address
Mumbai,India

Using Form collection Class Object

  1. [HttpPost]  
  2. public ActionResult EmployeeResult(FormCollection frmObj)  
  3. {  
  4.     string name = frmObj["EmployeeName"].ToString();  
  5.     string number = frmObj["EmployeeNumber"].ToString();  
  6.     string address = frmObj["EmployeeAddress"].ToString();  
  7.     StringBuilder strs = new StringBuilder();  
  8.     strs.Append("<b>Name:</b> " + name + "<br/>");  
  9.     strs.Append("<b>Number:</b> " + number + "<br/>");  
  10.     strs.Append("<b>Address :</b> " + address + "<br/>");  
  11. }  
Rest View will be the same.