Getting Data From View to Controller in MVC

this article explains how to access data from a view to the controller's action method. The action method is a simple C# method that can be parameterized or without a parameter in the controller.

We use two types of methods to handle our browser request; one is HTTP GET and another is HTTP POST. When we call an action method by a request's URL by the browser then the HTTP GET method will be called but when a request is from a button click event then the HTTP POST method will be called. So in this article I am going to explaining how to access view input field data in the controller's action method when a HTTP POST request is called.

To understand how to access view input field data in the controller's action method (POST), we create a "Calculate Simple Interest" application. This application gets Principle, Rate and Time as user input and generates simple interest. So let's proceed with the application.

Create an action method in the CalculateSimpleInterest controller (CalculateSimpleInterestController.cs) that renders the view on the UI.

  1. public ActionResult SimpleInterest()  
  2. {  
  3.     return View();  
  4. }  

Create a view to get user input from the UI, so the code is:

  1. <h2>Calculate Simple Interest</h2>  
  2. <fieldset>  
  3.         <legend>Calculate Simple Interest</legend>  
  4.     @using (Ajax.BeginForm("CalculateSimpleInterestResult","CalculateSimpleInterest",  
  5.                             new AjaxOptions { UpdateTargetId = "divInterestDeatils" }))  
  6.     {  
  7.         <div id="divInterestDeatils"></div>  
  8.         <ol>  
  9.             <li>  
  10.                 @Html.Label("Amount")  
  11.                 @Html.TextBox("txtAmount")  
  12.             </li>  
  13.             <li>  
  14.                 @Html.Label("Rate")  
  15.                 @Html.TextBox("txtRate")  
  16.             </li>  
  17.             <li>  
  18.                 @Html.Label("Year")  
  19.                 @Html.TextBox("txtYear")  
  20.             </li>  
  21.         </ol>  
  22.     <button>Calculate</button>  
  23.     }     
  24. </fieldset>  

So now the screen is ready to get input and it shows it as:

MVC.jpg

Figure 1.1 Input screens to calculate simple interest

I will now explain the four ways to get the view's data in the controller action. These are:

  1. Using Traditional approach

  2. Using the FormCollection Object

  3. Using the Parameters

  4. Strongly type model binding to view

Using Traditional Approach

In the traditional approach we use the request object of the HttpRequestBase class. The request object has view input field values in name/value pairs. When we create a submit button then the request type POST is created and calls the POST method.

MVC1.jpg

Figure 1.2 Requested Data

We have four data, those are 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 get values. Our POST method means the controller action that handles the POST request type is
[HttpPost].

  1. [HttpPost]  
  2. public ActionResult CalculateSimpleInterestResult()  
  3. {  
  4.     decimal principle = Convert.ToDecimal(Request["txtAmount"].ToString());  
  5.     decimal rate = Convert.ToDecimal(Request["txtRate"].ToString());  
  6.     int time = Convert.ToInt32(Request["txtYear"].ToString());  
  7.    
  8.     decimal simpleInteresrt = (principle*time*rate)/100;  
  9.    
  10.     StringBuilder sbInterest = new StringBuilder();  
  11.     sbInterest.Append("<b>Amount :</b> " + principle+"<br/>");  
  12.     sbInterest.Append("<b>Rate :</b> " + rate + "<br/>");  
  13.     sbInterest.Append("<b>Time(year) :</b> " + time + "<br/>");  
  14.     sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);  
  15.     return Content(sbInterest.ToString());  
  16. }  

When it executes, we get simple interest as the result as in the following:

MVC2.jpg

Figure 1.3 Output screen after getting response

Using the FormCollection Object

We can also get post requested data by the FormCollection object. The FormCollection object also has requested data in the name/value collection as the Request object. To get data from the FormCollection object we need to pass it is as a parameter and it has all the input field data submitted on the form.

  1. [HttpPost]  
  2.   
  3. public ActionResult CalculateSimpleInterestResult(FormCollection form)  
  4. {  
  5.     decimal principle = Convert.ToDecimal(form["txtAmount"].ToString());  
  6.     decimal rate = Convert.ToDecimal(form["txtRate"].ToString());  
  7.     int time = Convert.ToInt32(form["txtYear"].ToString());  
  8.    
  9.     decimal simpleInteresrt = (principle*time*rate)/100;  
  10.    
  11.     StringBuilder sbInterest = new StringBuilder();  
  12.     sbInterest.Append("<b>Amount :</b> " + principle+"<br/>");  
  13.     sbInterest.Append("<b>Rate :</b> " + rate + "<br/>");  
  14.     sbInterest.Append("<b>Time(year) :</b> " + time + "<br/>");  
  15.     sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);  
  16.     return Content(sbInterest.ToString());  

It also gives the same output as Figure 1.3 shows.

Using the Parameters

We can pass all input field names as a parameter to the post action method. The input field name and parameter name should be the same. These parameters have input field values that were entered by the user. So we can access view input field values from these parameters. The input field takes a string value from the user so the parameter should be a string type. There is no need to define a parameter in any specific sequence.

  1. [HttpPost]  
  2. public ActionResult CalculateSimpleInterestResult(string txtAmount, string txtRate, string txtYear)  
  3. {  
  4.     decimal principle = Convert.ToDecimal(txtAmount);  
  5.     decimal rate = Convert.ToDecimal(txtRate);  
  6.     int time = Convert.ToInt32(txtYear);  
  7.    
  8.     decimal simpleInteresrt = (principle*time*rate)/100;  
  9.    
  10.     StringBuilder sbInterest = new StringBuilder();  
  11.     sbInterest.Append("<b>Amount :</b> " + principle+"<br/>");  
  12.     sbInterest.Append("<b>Rate :</b> " + rate + "<br/>");  
  13.     sbInterest.Append("<b>Time(year) :</b> " + time + "<br/>");  
  14.     sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);  
  15.     return Content(sbInterest.ToString());  
  16. }  
It also gives the same output as Figure 1.3 shows.

In all three approaches above we are parsing the string to a non-string type. If any of the parsing attempts fail then the entire action will fail. We are converting each value to avoid an exception but it also increases the amount of code. So we look at the fourth approach that would reduce the amount of code.

Strongly type model binding to view


We bind a model to the view; that is called strongly type model binding.

Step 1

Create a Model for Simple Interest

  1. namespace CalculateSimpleInterest.Models  
  2. {  
  3.     public class SimpleInterestModel  
  4.     {  
  5.         public decimal Amount { get; set; }  
  6.         public decimal Rate { get; set; }  
  7.         public int Year { get; set; }  
  8.     }  
  9. }  

Step 2

Create an action method that render a view on the UI

We are passing an empty model to be bound to the view.

  1. public ActionResult SimpleInterest()  
  2. {  
  3.     SimpleInterestModel model = new SimpleInterestModel();  
  4.     return View(model);  
  5. }  

Step 3

Create a strongly typed view that has the same screen as in Figure 1.1

  1. @model CalculateSimpleInterest.Models.SimpleInterestModel  
  2.    
  3. @{  
  4.     ViewBag.Title = "SimpleInterest";  
  5. }  
  6.    
  7. <h2>Calulate Simple Interest</h2>  
  8.    
  9. @using (Ajax.BeginForm("CalculateSimpleInterestResult","CalculateSimpleInterest",  
  10.                             new AjaxOptions { UpdateTargetId = "divInterestDeatils" }))  
  11.     {  
  12.          
  13.     <fieldset>  
  14.         <legend>Calulate Simple Interest</legend>  
  15.         <div id="divInterestDeatils"></div>  
  16.    
  17.         <div class="editor-label">  
  18.             @Html.LabelFor(model => model.Amount)  
  19.         </div>  
  20.         <div class="editor-field">  
  21.             @Html.EditorFor(model => model.Amount)            
  22.         </div>  
  23.    
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(model => model.Rate)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.Rate)            
  29.         </div>  
  30.    
  31.         <div class="editor-label">  
  32.             @Html.LabelFor(model => model.Year)  
  33.         </div>  
  34.         <div class="editor-field">  
  35.             @Html.EditorFor(model => model.Year)             
  36.         </div>  
  37.         <p>  
  38.             <input type="submit" value="Calculate" />  
  39.         </p>  
  40.     </fieldset>  
  41. }  
  42.    
  43. @section Scripts {  
  44.     @Scripts.Render("~/bundles/jqueryval")  
  45. }  

Step 4

Create an action method that handles the POST request and processes the data

In the action method we pass a model as the parameter. That model has UI input field data. Here we do not need to parse and do not need to write extra code.

  1. [HttpPost]  
  2. public ActionResult CalculateSimpleInterestResult(SimpleInterestModel model)  
  3. {  
  4.     decimal simpleInteresrt = (model.Amount*model.Year*model.Rate)/100;  
  5.     StringBuilder sbInterest = new StringBuilder();  
  6.     sbInterest.Append("<b>Amount :</b> " + model.Amount+"<br/>");  
  7.     sbInterest.Append("<b>Rate :</b> " + model.Rate + "<br/>");  
  8.     sbInterest.Append("<b>Time(year) :</b> " + model.Year + "<br/>");  
  9.     sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);  
  10.     return Content(sbInterest.ToString());  
  11. }  

It also gives the same output as Figure 1.3 shows.

Next Recommended Readings